diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs index 1c67afe262..b6c77c84af 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs @@ -51,7 +51,7 @@ public class Serialize : UnitsNetJsonConverterTests public void Information_CanSerializeVeryLargeValues() { Information i = Information.FromExabytes(1E+9); - var expectedJson = "{\n \"Unit\": \"InformationUnit.Bit\",\n \"Value\": 8E+27\n}"; + var expectedJson = "{\n \"Unit\": \"InformationUnit.Exabyte\",\n \"Value\": 1000000000.0\n}"; string json = SerializeObject(i); @@ -59,16 +59,27 @@ public void Information_CanSerializeVeryLargeValues() } [Fact] - public void Mass_ExpectKilogramsUsedAsBaseValueAndUnit() + public void Mass_ExpectConstructedValueAndUnit() { Mass mass = Mass.FromPounds(200); - var expectedJson = "{\n \"Unit\": \"MassUnit.Kilogram\",\n \"Value\": 90.718474\n}"; + var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; string json = SerializeObject(mass); Assert.Equal(expectedJson, json); } + [Fact] + public void Information_ExpectConstructedValueAndUnit() + { + Information quantity = Information.FromKilobytes(54); + var expectedJson = "{\n \"Unit\": \"InformationUnit.Kilobyte\",\n \"Value\": 54.0\n}"; + + string json = SerializeObject(quantity); + + Assert.Equal(expectedJson, json); + } + [Fact] public void NonNullNullableValue_ExpectJsonUnaffected() { @@ -122,7 +133,7 @@ public void NullValue_ExpectJsonContainsNullString() public void Ratio_ExpectDecimalFractionsUsedAsBaseValueAndUnit() { Ratio ratio = Ratio.FromPartsPerThousand(250); - var expectedJson = "{\n \"Unit\": \"RatioUnit.DecimalFraction\",\n \"Value\": 0.25\n}"; + var expectedJson = "{\n \"Unit\": \"RatioUnit.PartPerThousand\",\n \"Value\": 250.0\n}"; string json = SerializeObject(ratio); @@ -376,4 +387,4 @@ private class TestObjWithThreeIComparable public IComparable Value3 { get; set; } } } -} \ No newline at end of file +} diff --git a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Signed.csproj b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Signed.csproj index 2cfc23a768..a937d99f20 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Signed.csproj +++ b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.Signed.csproj @@ -9,6 +9,7 @@ + SIGNED true $(MSBuildProjectDirectory)\..\UnitsNet.snk diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs index 4e92690a71..024acf53b1 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs @@ -20,18 +20,19 @@ // THE SOFTWARE. using System; -using System.Globalization; using System.Linq; using System.Reflection; using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using UnitsNet.InternalHelpers; namespace UnitsNet.Serialization.JsonNet { + /// /// - /// A JSON.net for converting to/from JSON and Units.NET - /// units like and . + /// A JSON.net for converting to/from JSON and Units.NET + /// units like and . /// /// /// Relies on reflection and the type names and namespaces as of 3.x.x of Units.NET. @@ -42,6 +43,11 @@ namespace UnitsNet.Serialization.JsonNet /// public class UnitsNetJsonConverter : JsonConverter { + /// + /// Numeric value field of a quantity, typically of type double or decimal. + /// + private const string ValueFieldName = "_value"; + /// /// Reads the JSON representation of the object. /// @@ -61,9 +67,8 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return reader.Value; } object obj = TryDeserializeIComparable(reader, serializer); - var vu = obj as ValueUnit; // A null System.Nullable value or a comparable type was deserialized so return this - if (vu == null) + if (!(obj is ValueUnit vu)) { return obj; } @@ -73,53 +78,82 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist string unitEnumValue = vu.Unit.Split('.')[1]; // "MassUnit" => "Mass" - string unitTypeName = unitEnumTypeName.Substring(0, unitEnumTypeName.Length - "Unit".Length); + string quantityTypeName = unitEnumTypeName.Substring(0, unitEnumTypeName.Length - "Unit".Length); // "UnitsNet.Units.MassUnit,UnitsNet" string unitEnumTypeAssemblyQualifiedName = "UnitsNet.Units." + unitEnumTypeName + ",UnitsNet"; // "UnitsNet.Mass,UnitsNet" - string unitTypeAssemblyQualifiedName = "UnitsNet." + unitTypeName + ",UnitsNet"; + string quantityTypeAssemblyQualifiedName = "UnitsNet." + quantityTypeName + ",UnitsNet"; // -- see http://stackoverflow.com/a/6465096/1256096 for details - Type reflectedUnitEnumType = Type.GetType(unitEnumTypeAssemblyQualifiedName); - if (reflectedUnitEnumType == null) + Type unitEnumType = Type.GetType(unitEnumTypeAssemblyQualifiedName); + if (unitEnumType == null) { var ex = new UnitsNetException("Unable to find enum type."); ex.Data["type"] = unitEnumTypeAssemblyQualifiedName; throw ex; } - Type reflectedUnitType = Type.GetType(unitTypeAssemblyQualifiedName); - if (reflectedUnitType == null) + Type quantityType = Type.GetType(quantityTypeAssemblyQualifiedName); + if (quantityType == null) { var ex = new UnitsNetException("Unable to find unit type."); - ex.Data["type"] = unitTypeAssemblyQualifiedName; + ex.Data["type"] = quantityTypeAssemblyQualifiedName; throw ex; } - object unit = Enum.Parse(reflectedUnitEnumType, unitEnumValue); + double value = vu.Value; + object unitValue = Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram - // Mass.From() method, assume no overloads exist - var fromMethod = reflectedUnitType -#if (NETSTANDARD1_0) - .GetTypeInfo() - .GetDeclaredMethods("From") - .Single(m => !m.ReturnType.IsConstructedGenericType); -#else - .GetMethods() - .Single(m => m.Name.Equals("From", StringComparison.InvariantCulture) && - !m.ReturnType.IsGenericType); -#endif + return CreateQuantity(quantityType, value, unitValue); + } - // Implicit cast: we use this type to avoid explosion of method overloads to handle multiple number types - QuantityValue quantityValue = vu.Value; + /// + /// Creates a quantity (ex: Mass) based on the reflected quantity type, a numeric value and a unit value (ex: MassUnit.Kilogram). + /// + /// Type of quantity, such as . + /// Numeric value. + /// The unit, such as . + /// The constructed quantity, such as . + private static object CreateQuantity(Type quantityType, double value, object unitValue) + { + // We want the non-nullable return type, example candidates if quantity type is Mass: + // double Mass.From(double, MassUnit) + // double? Mass.From(double?, MassUnit) + MethodInfo notNullableFromMethod = quantityType + .GetDeclaredMethods() + .Single(m => m.Name == "From" && Nullable.GetUnderlyingType(m.ReturnType) == null); + + // Of type QuantityValue + object quantityValue = GetFromMethodValueArgument(notNullableFromMethod, value); // Ex: Mass.From(55, MassUnit.Gram) // TODO: there is a possible loss of precision if base value requires higher precision than double can represent. // Example: Serializing Information.FromExabytes(100) then deserializing to Information // will likely return a very different result. Not sure how we can handle this? - return fromMethod.Invoke(null, new[] {quantityValue, unit}); + return notNullableFromMethod.Invoke(null, new[] {quantityValue, unitValue}); + } + + /// + /// Returns numeric value wrapped as , based on the type of argument + /// of . Today this is always , but + /// we may extend to other types later such as QuantityValueDecimal. + /// + /// The reflected From(value, unit) method. + /// The value to convert to the correct wrapper type. + /// + private static object GetFromMethodValueArgument(MethodInfo fromMethod, double value) + { + Type valueParameterType = fromMethod.GetParameters()[0].ParameterType; + if (valueParameterType == typeof(QuantityValue)) + { + // We use this type that takes implicit cast from all number types to avoid explosion of method overloads that take a numeric value. + return (QuantityValue) value; + } + + throw new Exception( + $"The first parameter of the reflected quantity From() method was expected to be either UnitsNet.QuantityValue, but was instead {valueParameterType}."); } private static object TryDeserializeIComparable(JsonReader reader, JsonSerializer serializer) @@ -147,77 +181,96 @@ private static object TryDeserializeIComparable(JsonReader reader, JsonSerialize /// Writes the JSON representation of the object. /// /// The to write to. - /// The value to write. + /// The value to write. /// The calling serializer. /// Can't serialize 'null' value. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object obj, JsonSerializer serializer) { - Type unitType = value.GetType(); + Type quantityType = obj.GetType(); // ValueUnit should be written as usual (but read in a custom way) - if(unitType == typeof(ValueUnit)) + if(quantityType == typeof(ValueUnit)) { JsonSerializer localSerializer = new JsonSerializer() { TypeNameHandling = serializer.TypeNameHandling, }; - JToken t = JToken.FromObject(value, localSerializer); + JToken t = JToken.FromObject(obj, localSerializer); t.WriteTo(writer); return; } + + object quantityValue = GetValueOfQuantity(obj, quantityType); // double or decimal value + string quantityUnitName = GetUnitFullNameOfQuantity(obj, quantityType); // Example: "MassUnit.Kilogram" + + serializer.Serialize(writer, new ValueUnit + { + // TODO Should we serialize long, decimal and long differently? + Value = Convert.ToDouble(quantityValue), + Unit = quantityUnitName + }); + } + + /// + /// Given quantity (ex: ), returns the full name (ex: "MassUnit.Kilogram") of the constructed unit given by the property. + /// + /// Quantity, such as . + /// The type of , passed in here to reuse a previous lookup. + /// "MassUnit.Kilogram" for a mass quantity whose Unit property is MassUnit.Kilogram. + private static string GetUnitFullNameOfQuantity(object obj, Type quantityType) + { + // Get value of Unit property + PropertyInfo unitProperty = quantityType.GetPropety("Unit"); + Enum quantityUnit = (Enum) unitProperty.GetValue(obj, null); // MassUnit.Kilogram + + Type unitType = quantityUnit.GetType(); // MassUnit + return $"{unitType.Name}.{quantityUnit}"; // "MassUnit.Kilogram" + } + + private static object GetValueOfQuantity(object value, Type quantityType) + { + FieldInfo valueField = GetPrivateInstanceField(quantityType, ValueFieldName); + + // Unit base type can be double, long or decimal, + // so make sure we serialize the real type to avoid + // loss of precision + object quantityValue = valueField.GetValue(value); + return quantityValue; + } + + private static FieldInfo GetPrivateInstanceField(Type quantityType, string fieldName) + { FieldInfo baseValueField; try { - baseValueField = unitType + baseValueField = quantityType #if (NETSTANDARD1_0) .GetTypeInfo() - .DeclaredFields - .SingleOrDefault(f => !f.IsPublic && !f.IsStatic); + .Where(f => !f.IsPublic && !f.IsStatic) #else .GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) - .SingleOrDefault(); #endif + .SingleOrDefault(f => f.Name == fieldName); } catch (InvalidOperationException) { - var ex = new UnitsNetException("Expected exactly 1 private field, but found multiple."); - ex.Data["type"] = unitType; + var ex = new UnitsNetException($"Expected exactly one private field named [{fieldName}], but found multiple."); + ex.Data["type"] = quantityType; + ex.Data["fieldName"] = fieldName; throw ex; } + if (baseValueField == null) { var ex = new UnitsNetException("No private fields found in type."); - ex.Data["type"] = unitType; + ex.Data["type"] = quantityType; + ex.Data["fieldName"] = fieldName; throw ex; } - // Unit base type can be double, long or decimal, - // so make sure we serialize the real type to avoid - // loss of precision - object baseValue = baseValueField.GetValue(value); - - // Mass => "MassUnit.Kilogram" - PropertyInfo baseUnitPropInfo = unitType -#if (NETSTANDARD1_0) - .GetTypeInfo() - .GetDeclaredProperty("BaseUnit"); -#else - .GetProperty("BaseUnit"); -#endif - // Read static BaseUnit property value - var baseUnitEnumValue = (Enum) baseUnitPropInfo.GetValue(null, null); - Type baseUnitType = baseUnitEnumValue.GetType(); - string baseUnit = $"{baseUnitType.Name}.{baseUnitEnumValue}"; - - serializer.Serialize(writer, new ValueUnit - { - // This might throw OverflowException for very large values? - // TODO Should we serialize long, decimal and long differently? - Value = Convert.ToDouble(baseValue), - Unit = baseUnit - }); + return baseValueField; } /// @@ -261,7 +314,7 @@ public override bool CanConvert(Type objectType) /// /// Type of the object. /// true if the object type is nullable; otherwise false. - protected bool IsNullable(Type objectType) + private static bool IsNullable(Type objectType) { return Nullable.GetUnderlyingType(objectType) != null; } @@ -280,4 +333,4 @@ protected virtual bool CanConvertNullable(Type objectType) #endregion } -} \ No newline at end of file +} diff --git a/UnitsNet.Tests/QuantityTests.Ctor.cs b/UnitsNet.Tests/QuantityTests.Ctor.cs new file mode 100644 index 0000000000..ff13b7293d --- /dev/null +++ b/UnitsNet.Tests/QuantityTests.Ctor.cs @@ -0,0 +1,114 @@ +using System.Diagnostics.CodeAnalysis; +using JetBrains.Annotations; +using UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests +{ + [UsedImplicitly] + public partial class QuantityTests + { + /// + /// Tests constructors of quantity types. + /// + public class Ctor + { + [Fact] + [SuppressMessage("ReSharper", "ObjectCreationAsStatement", Justification = "Only testing the ctor itself, not the resulting value.")] + public void DefaultCtorOfRepresentativeTypes_DoesNotThrow() + { + // double types + new Length(); + + // decimal types + new Information(); + + // logarithmic types + new Level(); + } + + [Fact] + public void DefaultCtorOfRepresentativeTypes_SetsValueToZeroAndUnitToBaseUnit() + { + // double types + Assert.Equal(0, new Mass().Value); + Assert.Equal(MassUnit.Kilogram, new Mass().Unit); + + // decimal types + Assert.Equal(0, new Information().Value); + Assert.Equal(InformationUnit.Bit, new Information().Unit); + + // logarithmic types + Assert.Equal(0, new Level().Value); + Assert.Equal(LevelUnit.Decibel, new Level().Unit); + } + + /// + /// This test is a bit misplaced, but was added because when working on #389 unit+value there were two + /// ways to implement this; either assume BaseUnit of unit is not specified or throw if quantity did not have unit explicitly set. + /// Struct types do not allow custom default ctor implementations, so that exception would then be thrown when trying to convert. + /// + [Fact] + public void DefaultCtorOfRepresentativeTypes_DoesNotThrowWhenConvertingToOtherUnits() + { + // double types + Assert.Equal(0, new Mass().Hectograms); + + // decimal types + Assert.Equal(0, new Information().Kibibits); + + // logarithmic types + Assert.Equal(0, new Level().Nepers); + } + + [Fact] + public void CtorWithOnlyValueOfRepresentativeTypes_SetsValueToGivenValueAndUnitToBaseUnit() + { +#pragma warning disable 618 + // double types + Assert.Equal(5, new Mass(5L).Value); + Assert.Equal(5, new Mass(5d).Value); + Assert.Equal(5, new Mass(5m).Value); + Assert.Equal(MassUnit.Kilogram, new Mass(5L).Unit); + Assert.Equal(MassUnit.Kilogram, new Mass(5d).Unit); + Assert.Equal(MassUnit.Kilogram, new Mass(5m).Unit); + + // decimal types + Assert.Equal(5, new Information(5L).Value); + Assert.Equal(5, new Information(5d).Value); + Assert.Equal(5, new Information(5m).Value); + Assert.Equal(InformationUnit.Bit, new Information(5L).Unit); + Assert.Equal(InformationUnit.Bit, new Information(5d).Unit); + Assert.Equal(InformationUnit.Bit, new Information(5m).Unit); + + // logarithmic types + Assert.Equal(5, new Level(5L).Value); + Assert.Equal(5, new Level(5d).Value); + Assert.Equal(5, new Level(5m).Value); + Assert.Equal(LevelUnit.Decibel, new Level(5L).Unit); + Assert.Equal(LevelUnit.Decibel, new Level(5d).Unit); + Assert.Equal(LevelUnit.Decibel, new Level(5m).Unit); +#pragma warning restore 618 + } + + [Fact] + public void CtorWithValueAndUnitOfRepresentativeTypes_SetsValueAndUnit() + { + // double types + var mass = new Mass(5L, MassUnit.Centigram); + Assert.Equal(5, mass.Value); + Assert.Equal(MassUnit.Centigram, mass.Unit); + + // decimal types + var information = new Information(5, InformationUnit.Kibibit); + Assert.Equal(5, information.Value); + Assert.Equal(InformationUnit.Kibibit, information.Unit); + + // logarithmic types + var level = new Level(5, LevelUnit.Neper); + Assert.Equal(5, level.Value); + Assert.Equal(LevelUnit.Neper, level.Unit); + } + } + } +} diff --git a/UnitsNet.Tests/QuantityTests.ToString.cs b/UnitsNet.Tests/QuantityTests.ToString.cs new file mode 100644 index 0000000000..940e9e21fa --- /dev/null +++ b/UnitsNet.Tests/QuantityTests.ToString.cs @@ -0,0 +1,157 @@ +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). +// https://github.com/angularsen/UnitsNet +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System.Globalization; +using UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests +{ + public partial class QuantityTests + { + public class ToString + { + [Fact] + public void CreatedByDefaultCtor_ReturnsValueInBaseUnit() + { + // double types + Assert.Equal("0 kg", new Mass().ToString()); + + // decimal types + Assert.Equal("0 b", new Information().ToString()); + + // logarithmic types + Assert.Equal("0 dB", new Level().ToString()); + } + + [Fact] + public void CreatedByCtorWithValue_ReturnsValueInBaseUnit() + { +#pragma warning disable 618 + // double types + Assert.Equal("5 kg", new Mass(5L).ToString()); + Assert.Equal("5 kg", new Mass(5d).ToString()); + Assert.Equal("5 kg", new Mass(5m).ToString()); + + // decimal types + Assert.Equal("5 b", new Information(5L).ToString()); + Assert.Equal("5 b", new Information(5d).ToString()); + Assert.Equal("5 b", new Information(5m).ToString()); + + // logarithmic types + Assert.Equal("5 dB", new Level(5L).ToString()); + Assert.Equal("5 dB", new Level(5d).ToString()); + Assert.Equal("5 dB", new Level(5m).ToString()); +#pragma warning restore 618 + } + + [Fact] + public void CreatedByCtorWithValueAndUnit_ReturnsValueAndUnit() + { +#pragma warning disable 618 + // double types + Assert.Equal("5 hg", new Mass(5, MassUnit.Hectogram).ToString()); + + // decimal types + Assert.Equal("8 B", new Information(8, InformationUnit.Byte).ToString()); + + // logarithmic types + Assert.Equal("5 Np", new Level(5, LevelUnit.Neper).ToString()); +#pragma warning restore 618 + } + + [Fact] + public void ReturnsTheOriginalValueAndUnit() + { + var oldCulture = UnitSystem.DefaultCulture; + try + { + UnitSystem.DefaultCulture = CultureInfo.InvariantCulture; + Assert.Equal("5 kg", Mass.FromKilograms(5).ToString()); + Assert.Equal("5,000 g", Mass.FromGrams(5000).ToString()); + Assert.Equal("1e-04 long tn", Mass.FromLongTons(1e-4).ToString()); + Assert.Equal("3.46e-04 dN/m", ForcePerLength.FromDecinewtonsPerMeter(0.00034567).ToString()); + Assert.Equal("0.0069 dB", Level.FromDecibels(0.0069).ToString()); + Assert.Equal("0.011 kWh/kg", SpecificEnergy.FromKilowattHoursPerKilogram(0.011).ToString()); + // Assert.Equal("0.1 MJ/kg·C", SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(0.1).ToString()); + Assert.Equal("0.1 MJ/kg.C", SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(0.1).ToString()); + Assert.Equal("5 cm", Length.FromCentimeters(5).ToString()); + } + finally + { + UnitSystem.DefaultCulture = oldCulture; + } + } + + [Fact] + public void ConvertsToTheGivenUnit() + { + var oldCulture = UnitSystem.DefaultCulture; + try + { + UnitSystem.DefaultCulture = CultureInfo.InvariantCulture; + Assert.Equal("5,000 g", Mass.FromKilograms(5).ToString(MassUnit.Gram)); + Assert.Equal("5 kg", Mass.FromGrams(5000).ToString(MassUnit.Kilogram)); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToString(LengthUnit.Meter)); + Assert.Equal("1.97 in", Length.FromCentimeters(5).ToString(LengthUnit.Inch)); + } + finally + { + UnitSystem.DefaultCulture = oldCulture; + } + } + + [Fact] + public void FormatsNumberUsingGivenCulture() + { + var oldCulture = UnitSystem.DefaultCulture; + try + { + UnitSystem.DefaultCulture = CultureInfo.InvariantCulture; + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToString(LengthUnit.Meter, null)); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToString(LengthUnit.Meter, CultureInfo.InvariantCulture)); + Assert.Equal("0,05 m", Length.FromCentimeters(5).ToString(LengthUnit.Meter, new CultureInfo("nb-NO"))); + } + finally + { + UnitSystem.DefaultCulture = oldCulture; + } + } + + [Fact] + public void FormatsNumberUsingGivenDigitsAfterRadix() + { + var oldCulture = UnitSystem.DefaultCulture; + try + { + UnitSystem.DefaultCulture = CultureInfo.InvariantCulture; + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToString(LengthUnit.Meter, null, 4)); + Assert.Equal("1.97 in", Length.FromCentimeters(5).ToString(LengthUnit.Inch, null, 2)); + Assert.Equal("1.9685 in", Length.FromCentimeters(5).ToString(LengthUnit.Inch, null, 4)); + } + finally + { + UnitSystem.DefaultCulture = oldCulture; + } + } + } + } +} diff --git a/UnitsNet.Tests/UnitsNet.Tests.csproj b/UnitsNet.Tests/UnitsNet.Tests.csproj index 3e521dcf5e..5d5565141e 100644 --- a/UnitsNet.Tests/UnitsNet.Tests.csproj +++ b/UnitsNet.Tests/UnitsNet.Tests.csproj @@ -13,6 +13,7 @@ + diff --git a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs index 688089bff7..471a09498a 100644 --- a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs @@ -20,6 +20,7 @@ // THE SOFTWARE. using System; +using UnitsNet.Units; namespace UnitsNet { @@ -55,7 +56,8 @@ public partial struct AmplitudeRatio "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)) - _decibelVolts = 20 * Math.Log10(voltage.Volts / 1); + _value = 20 * Math.Log10(voltage.Volts / 1); + _unit = AmplitudeRatioUnit.DecibelVolt; } /// @@ -75,7 +77,7 @@ public static AmplitudeRatio FromElectricPotential(ElectricPotential voltage) public static ElectricPotential ToElectricPotential(AmplitudeRatio voltageRatio) { // E(V) = 1V * 10^(E(dBV)/20) - return ElectricPotential.FromVolts(Math.Pow(10, voltageRatio._decibelVolts / 20)); + return ElectricPotential.FromVolts(Math.Pow(10, voltageRatio.DecibelVolts / 20)); } /// @@ -90,4 +92,4 @@ public static PowerRatio ToPowerRatio(AmplitudeRatio amplitudeRatio, ElectricRes return PowerRatio.FromDecibelWatts(amplitudeRatio.DecibelVolts - 10 * Math.Log10(impedance.Ohms / 1)); } } -} \ No newline at end of file +} diff --git a/UnitsNet/CustomCode/Quantities/Level.extra.cs b/UnitsNet/CustomCode/Quantities/Level.extra.cs index 404765017b..34bac448cc 100644 --- a/UnitsNet/CustomCode/Quantities/Level.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Level.extra.cs @@ -20,17 +20,16 @@ // THE SOFTWARE. using System; +using UnitsNet.Units; namespace UnitsNet { // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. -#if WINDOWS_UWP - public sealed partial class Level -#else + // Cannot have methods with same name and same number of parameters. +#if !WINDOWS_UWP public partial struct Level -#endif { /// /// Initializes a new instance of the logarithmic struct which is the ratio of a quantity Q to a @@ -49,7 +48,9 @@ public Level(double quantity, double reference) if ((reference == 0) || ((quantity > 0) && (reference < 0))) throw new ArgumentOutOfRangeException(nameof(reference), errorMessage); - _decibels = 10*Math.Log10(quantity/reference); + _value = 10*Math.Log10(quantity/reference); + _unit = LevelUnit.Decibel; } } -} \ No newline at end of file +#endif +} diff --git a/UnitsNet/CustomCode/Quantities/Molarity.extra.cs b/UnitsNet/CustomCode/Quantities/Molarity.extra.cs index c549b2fc67..62a53f86c9 100644 --- a/UnitsNet/CustomCode/Quantities/Molarity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Molarity.extra.cs @@ -1,4 +1,5 @@ using System; +using UnitsNet.Units; namespace UnitsNet { @@ -20,7 +21,8 @@ public partial struct Molarity Molarity(Density density, Mass molecularWeight) : this() { - _molesPerCubicMeter = density.KilogramsPerCubicMeter / molecularWeight.Kilograms; + _value = density.KilogramsPerCubicMeter / molecularWeight.Kilograms; + _unit = MolarityUnit.MolesPerCubicMeter; } /// diff --git a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs index 8f3efdcfd4..3c4c490a2c 100644 --- a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs @@ -20,6 +20,7 @@ // THE SOFTWARE. using System; +using UnitsNet.Units; namespace UnitsNet { @@ -51,7 +52,8 @@ public partial struct PowerRatio 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)) - _decibelWatts = 10 * Math.Log10(power.Watts / 1); + _value = 10 * Math.Log10(power.Watts / 1); + _unit = PowerRatioUnit.DecibelWatt; } /// @@ -70,7 +72,7 @@ public static PowerRatio FromPower(Power power) public static Power ToPower(PowerRatio powerRatio) { // P(W) = 1W * 10^(P(dBW)/10) - return Power.FromWatts(Math.Pow(10, powerRatio._decibelWatts / 10)); + return Power.FromWatts(Math.Pow(10, powerRatio.DecibelWatts / 10)); } /// @@ -85,4 +87,4 @@ public static AmplitudeRatio ToAmplitudeRatio(PowerRatio powerRatio, ElectricRes return AmplitudeRatio.FromDecibelVolts(10 * Math.Log10(impedance.Ohms / 1) + powerRatio.DecibelWatts); } } -} \ No newline at end of file +} diff --git a/UnitsNet/CustomCode/UnitSystem.cs b/UnitsNet/CustomCode/UnitSystem.cs index 23c49b2cb9..488e0d8098 100644 --- a/UnitsNet/CustomCode/UnitSystem.cs +++ b/UnitsNet/CustomCode/UnitSystem.cs @@ -137,8 +137,15 @@ public UnitSystem() : this(DefaultCulture) /// /// Defaults to when creating an instance with no culture provided. + /// Can be overridden, but note that this is static and will affect all subsequent usages. /// - private static IFormatProvider DefaultCulture => CultureInfo.CurrentUICulture; +#if WINDOWS_UWP + // Windows Runtime Component does not support exposing the IFormatProvider type in public API + internal +#else + public +#endif + static IFormatProvider DefaultCulture { get; set; } = CultureInfo.CurrentUICulture; public bool IsFallbackCulture => Culture.Equals(FallbackCulture); diff --git a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs index 6adfac903a..bb6813899e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Acceleration : IComparable, IComparable #endif { /// - /// Base unit of Acceleration. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AccelerationUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _meterPerSecondSquared; + public AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Acceleration() : this(0) + public Acceleration() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Acceleration(double meterpersecondsquared) { - _meterPerSecondSquared = Convert.ToDouble(meterpersecondsquared); + _value = Convert.ToDouble(meterpersecondsquared); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Acceleration(double numericValue, AccelerationUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit MeterPerSecondSquared. + /// + /// Value assuming base unit MeterPerSecondSquared. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Acceleration(long meterpersecondsquared) - { - _meterPerSecondSquared = Convert.ToDouble(meterpersecondsquared); - } + Acceleration(long meterpersecondsquared) : this(Convert.ToDouble(meterpersecondsquared), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit MeterPerSecondSquared. + /// + /// Value assuming base unit MeterPerSecondSquared. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Acceleration(decimal meterpersecondsquared) - { - _meterPerSecondSquared = Convert.ToDouble(meterpersecondsquared); - } + Acceleration(decimal meterpersecondsquared) : this(Convert.ToDouble(meterpersecondsquared), BaseUnit) { } #region Properties @@ -119,128 +156,70 @@ public Acceleration(double meterpersecondsquared) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static AccelerationUnit BaseUnit - { - get { return AccelerationUnit.MeterPerSecondSquared; } - } + public static AccelerationUnit BaseUnit => AccelerationUnit.MeterPerSecondSquared; /// /// All units of measurement for the Acceleration quantity. /// public static AccelerationUnit[] Units { get; } = Enum.GetValues(typeof(AccelerationUnit)).Cast().ToArray(); - /// /// Get Acceleration in CentimeterPerSecondSquared. /// - public double CentimeterPerSecondSquared - { - get { return (_meterPerSecondSquared) / 1e-2d; } - } - + public double CentimeterPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); /// /// Get Acceleration in DecimeterPerSecondSquared. /// - public double DecimeterPerSecondSquared - { - get { return (_meterPerSecondSquared) / 1e-1d; } - } - + public double DecimeterPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); /// /// Get Acceleration in FeetPerSecondSquared. /// - public double FeetPerSecondSquared - { - get { return _meterPerSecondSquared/0.304800; } - } - + public double FeetPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); /// /// Get Acceleration in InchesPerSecondSquared. /// - public double InchesPerSecondSquared - { - get { return _meterPerSecondSquared/0.0254; } - } - + public double InchesPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); /// /// Get Acceleration in KilometerPerSecondSquared. /// - public double KilometerPerSecondSquared - { - get { return (_meterPerSecondSquared) / 1e3d; } - } - + public double KilometerPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); /// /// Get Acceleration in KnotsPerHour. /// - public double KnotsPerHour - { - get { return _meterPerSecondSquared/0.5144444444444*3600; } - } - + public double KnotsPerHour => As(AccelerationUnit.KnotPerHour); /// /// Get Acceleration in KnotsPerMinute. /// - public double KnotsPerMinute - { - get { return _meterPerSecondSquared/0.5144444444444*60; } - } - + public double KnotsPerMinute => As(AccelerationUnit.KnotPerMinute); /// /// Get Acceleration in KnotsPerSecond. /// - public double KnotsPerSecond - { - get { return _meterPerSecondSquared/0.5144444444444; } - } - + public double KnotsPerSecond => As(AccelerationUnit.KnotPerSecond); /// /// Get Acceleration in MeterPerSecondSquared. /// - public double MeterPerSecondSquared - { - get { return _meterPerSecondSquared; } - } - + public double MeterPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); /// /// Get Acceleration in MicrometerPerSecondSquared. /// - public double MicrometerPerSecondSquared - { - get { return (_meterPerSecondSquared) / 1e-6d; } - } - + public double MicrometerPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); /// /// Get Acceleration in MillimeterPerSecondSquared. /// - public double MillimeterPerSecondSquared - { - get { return (_meterPerSecondSquared) / 1e-3d; } - } - + public double MillimeterPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); /// /// Get Acceleration in NanometerPerSecondSquared. /// - public double NanometerPerSecondSquared - { - get { return (_meterPerSecondSquared) / 1e-9d; } - } - + public double NanometerPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); /// /// Get Acceleration in StandardGravity. /// - public double StandardGravity - { - get { return _meterPerSecondSquared/9.80665; } - } + public double StandardGravity => As(AccelerationUnit.StandardGravity); #endregion #region Static - public static Acceleration Zero - { - get { return new Acceleration(); } - } + public static Acceleration Zero => new Acceleration(0, BaseUnit); /// /// Get Acceleration from CentimeterPerSecondSquared. @@ -248,17 +227,13 @@ public static Acceleration Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromCentimeterPerSecondSquared(double centimeterpersecondsquared) - { - double value = (double) centimeterpersecondsquared; - return new Acceleration((value) * 1e-2d); - } #else public static Acceleration FromCentimeterPerSecondSquared(QuantityValue centimeterpersecondsquared) +#endif { double value = (double) centimeterpersecondsquared; - return new Acceleration(((value) * 1e-2d)); + return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); } -#endif /// /// Get Acceleration from DecimeterPerSecondSquared. @@ -266,17 +241,13 @@ public static Acceleration FromCentimeterPerSecondSquared(QuantityValue centimet #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromDecimeterPerSecondSquared(double decimeterpersecondsquared) - { - double value = (double) decimeterpersecondsquared; - return new Acceleration((value) * 1e-1d); - } #else public static Acceleration FromDecimeterPerSecondSquared(QuantityValue decimeterpersecondsquared) +#endif { double value = (double) decimeterpersecondsquared; - return new Acceleration(((value) * 1e-1d)); + return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); } -#endif /// /// Get Acceleration from FeetPerSecondSquared. @@ -284,17 +255,13 @@ public static Acceleration FromDecimeterPerSecondSquared(QuantityValue decimeter #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromFeetPerSecondSquared(double feetpersecondsquared) - { - double value = (double) feetpersecondsquared; - return new Acceleration(value*0.304800); - } #else public static Acceleration FromFeetPerSecondSquared(QuantityValue feetpersecondsquared) +#endif { double value = (double) feetpersecondsquared; - return new Acceleration((value*0.304800)); + return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); } -#endif /// /// Get Acceleration from InchesPerSecondSquared. @@ -302,17 +269,13 @@ public static Acceleration FromFeetPerSecondSquared(QuantityValue feetperseconds #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromInchesPerSecondSquared(double inchespersecondsquared) - { - double value = (double) inchespersecondsquared; - return new Acceleration(value*0.0254); - } #else public static Acceleration FromInchesPerSecondSquared(QuantityValue inchespersecondsquared) +#endif { double value = (double) inchespersecondsquared; - return new Acceleration((value*0.0254)); + return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); } -#endif /// /// Get Acceleration from KilometerPerSecondSquared. @@ -320,17 +283,13 @@ public static Acceleration FromInchesPerSecondSquared(QuantityValue inchespersec #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromKilometerPerSecondSquared(double kilometerpersecondsquared) - { - double value = (double) kilometerpersecondsquared; - return new Acceleration((value) * 1e3d); - } #else public static Acceleration FromKilometerPerSecondSquared(QuantityValue kilometerpersecondsquared) +#endif { double value = (double) kilometerpersecondsquared; - return new Acceleration(((value) * 1e3d)); + return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); } -#endif /// /// Get Acceleration from KnotsPerHour. @@ -338,17 +297,13 @@ public static Acceleration FromKilometerPerSecondSquared(QuantityValue kilometer #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromKnotsPerHour(double knotsperhour) - { - double value = (double) knotsperhour; - return new Acceleration(value*0.5144444444444/3600); - } #else public static Acceleration FromKnotsPerHour(QuantityValue knotsperhour) +#endif { double value = (double) knotsperhour; - return new Acceleration((value*0.5144444444444/3600)); + return new Acceleration(value, AccelerationUnit.KnotPerHour); } -#endif /// /// Get Acceleration from KnotsPerMinute. @@ -356,17 +311,13 @@ public static Acceleration FromKnotsPerHour(QuantityValue knotsperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromKnotsPerMinute(double knotsperminute) - { - double value = (double) knotsperminute; - return new Acceleration(value*0.5144444444444/60); - } #else public static Acceleration FromKnotsPerMinute(QuantityValue knotsperminute) +#endif { double value = (double) knotsperminute; - return new Acceleration((value*0.5144444444444/60)); + return new Acceleration(value, AccelerationUnit.KnotPerMinute); } -#endif /// /// Get Acceleration from KnotsPerSecond. @@ -374,17 +325,13 @@ public static Acceleration FromKnotsPerMinute(QuantityValue knotsperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromKnotsPerSecond(double knotspersecond) - { - double value = (double) knotspersecond; - return new Acceleration(value*0.5144444444444); - } #else public static Acceleration FromKnotsPerSecond(QuantityValue knotspersecond) +#endif { double value = (double) knotspersecond; - return new Acceleration((value*0.5144444444444)); + return new Acceleration(value, AccelerationUnit.KnotPerSecond); } -#endif /// /// Get Acceleration from MeterPerSecondSquared. @@ -392,17 +339,13 @@ public static Acceleration FromKnotsPerSecond(QuantityValue knotspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromMeterPerSecondSquared(double meterpersecondsquared) - { - double value = (double) meterpersecondsquared; - return new Acceleration(value); - } #else public static Acceleration FromMeterPerSecondSquared(QuantityValue meterpersecondsquared) +#endif { double value = (double) meterpersecondsquared; - return new Acceleration((value)); + return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); } -#endif /// /// Get Acceleration from MicrometerPerSecondSquared. @@ -410,17 +353,13 @@ public static Acceleration FromMeterPerSecondSquared(QuantityValue meterpersecon #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromMicrometerPerSecondSquared(double micrometerpersecondsquared) - { - double value = (double) micrometerpersecondsquared; - return new Acceleration((value) * 1e-6d); - } #else public static Acceleration FromMicrometerPerSecondSquared(QuantityValue micrometerpersecondsquared) +#endif { double value = (double) micrometerpersecondsquared; - return new Acceleration(((value) * 1e-6d)); + return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); } -#endif /// /// Get Acceleration from MillimeterPerSecondSquared. @@ -428,17 +367,13 @@ public static Acceleration FromMicrometerPerSecondSquared(QuantityValue micromet #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromMillimeterPerSecondSquared(double millimeterpersecondsquared) - { - double value = (double) millimeterpersecondsquared; - return new Acceleration((value) * 1e-3d); - } #else public static Acceleration FromMillimeterPerSecondSquared(QuantityValue millimeterpersecondsquared) +#endif { double value = (double) millimeterpersecondsquared; - return new Acceleration(((value) * 1e-3d)); + return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); } -#endif /// /// Get Acceleration from NanometerPerSecondSquared. @@ -446,17 +381,13 @@ public static Acceleration FromMillimeterPerSecondSquared(QuantityValue millimet #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromNanometerPerSecondSquared(double nanometerpersecondsquared) - { - double value = (double) nanometerpersecondsquared; - return new Acceleration((value) * 1e-9d); - } #else public static Acceleration FromNanometerPerSecondSquared(QuantityValue nanometerpersecondsquared) +#endif { double value = (double) nanometerpersecondsquared; - return new Acceleration(((value) * 1e-9d)); + return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); } -#endif /// /// Get Acceleration from StandardGravity. @@ -464,17 +395,13 @@ public static Acceleration FromNanometerPerSecondSquared(QuantityValue nanometer #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Acceleration FromStandardGravity(double standardgravity) - { - double value = (double) standardgravity; - return new Acceleration(value*9.80665); - } #else public static Acceleration FromStandardGravity(QuantityValue standardgravity) +#endif { double value = (double) standardgravity; - return new Acceleration((value*9.80665)); + return new Acceleration(value, AccelerationUnit.StandardGravity); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -689,38 +616,7 @@ public static Acceleration From(double value, AccelerationUnit fromUnit) public static Acceleration From(QuantityValue value, AccelerationUnit fromUnit) #endif { - switch (fromUnit) - { - case AccelerationUnit.CentimeterPerSecondSquared: - return FromCentimeterPerSecondSquared(value); - case AccelerationUnit.DecimeterPerSecondSquared: - return FromDecimeterPerSecondSquared(value); - case AccelerationUnit.FootPerSecondSquared: - return FromFeetPerSecondSquared(value); - case AccelerationUnit.InchPerSecondSquared: - return FromInchesPerSecondSquared(value); - case AccelerationUnit.KilometerPerSecondSquared: - return FromKilometerPerSecondSquared(value); - case AccelerationUnit.KnotPerHour: - return FromKnotsPerHour(value); - case AccelerationUnit.KnotPerMinute: - return FromKnotsPerMinute(value); - case AccelerationUnit.KnotPerSecond: - return FromKnotsPerSecond(value); - case AccelerationUnit.MeterPerSecondSquared: - return FromMeterPerSecondSquared(value); - case AccelerationUnit.MicrometerPerSecondSquared: - return FromMicrometerPerSecondSquared(value); - case AccelerationUnit.MillimeterPerSecondSquared: - return FromMillimeterPerSecondSquared(value); - case AccelerationUnit.NanometerPerSecondSquared: - return FromNanometerPerSecondSquared(value); - case AccelerationUnit.StandardGravity: - return FromStandardGravity(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Acceleration((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -737,38 +633,8 @@ public static Acceleration From(QuantityValue value, AccelerationUnit fromUnit) { return null; } - switch (fromUnit) - { - case AccelerationUnit.CentimeterPerSecondSquared: - return FromCentimeterPerSecondSquared(value.Value); - case AccelerationUnit.DecimeterPerSecondSquared: - return FromDecimeterPerSecondSquared(value.Value); - case AccelerationUnit.FootPerSecondSquared: - return FromFeetPerSecondSquared(value.Value); - case AccelerationUnit.InchPerSecondSquared: - return FromInchesPerSecondSquared(value.Value); - case AccelerationUnit.KilometerPerSecondSquared: - return FromKilometerPerSecondSquared(value.Value); - case AccelerationUnit.KnotPerHour: - return FromKnotsPerHour(value.Value); - case AccelerationUnit.KnotPerMinute: - return FromKnotsPerMinute(value.Value); - case AccelerationUnit.KnotPerSecond: - return FromKnotsPerSecond(value.Value); - case AccelerationUnit.MeterPerSecondSquared: - return FromMeterPerSecondSquared(value.Value); - case AccelerationUnit.MicrometerPerSecondSquared: - return FromMicrometerPerSecondSquared(value.Value); - case AccelerationUnit.MillimeterPerSecondSquared: - return FromMillimeterPerSecondSquared(value.Value); - case AccelerationUnit.NanometerPerSecondSquared: - return FromNanometerPerSecondSquared(value.Value); - case AccelerationUnit.StandardGravity: - return FromStandardGravity(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Acceleration((double)value.Value, fromUnit); } #endif @@ -787,12 +653,29 @@ public static string GetAbbreviation(AccelerationUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(AccelerationUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + AccelerationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -803,37 +686,37 @@ public static string GetAbbreviation(AccelerationUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static Acceleration operator -(Acceleration right) { - return new Acceleration(-right._meterPerSecondSquared); + return new Acceleration(-right.Value, right.Unit); } public static Acceleration operator +(Acceleration left, Acceleration right) { - return new Acceleration(left._meterPerSecondSquared + right._meterPerSecondSquared); + return new Acceleration(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Acceleration operator -(Acceleration left, Acceleration right) { - return new Acceleration(left._meterPerSecondSquared - right._meterPerSecondSquared); + return new Acceleration(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Acceleration operator *(double left, Acceleration right) { - return new Acceleration(left*right._meterPerSecondSquared); + return new Acceleration(left * right.Value, right.Unit); } public static Acceleration operator *(Acceleration left, double right) { - return new Acceleration(left._meterPerSecondSquared*(double)right); + return new Acceleration(left.Value * right, left.Unit); } public static Acceleration operator /(Acceleration left, double right) { - return new Acceleration(left._meterPerSecondSquared/(double)right); + return new Acceleration(left.Value / right, left.Unit); } public static double operator /(Acceleration left, Acceleration right) { - return Convert.ToDouble(left._meterPerSecondSquared/right._meterPerSecondSquared); + return left.MeterPerSecondSquared / right.MeterPerSecondSquared; } #endif @@ -856,43 +739,43 @@ public int CompareTo(object obj) #endif int CompareTo(Acceleration other) { - return _meterPerSecondSquared.CompareTo(other._meterPerSecondSquared); + return AsBaseUnitMeterPerSecondSquared().CompareTo(other.AsBaseUnitMeterPerSecondSquared()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Acceleration left, Acceleration right) { - return left._meterPerSecondSquared <= right._meterPerSecondSquared; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Acceleration left, Acceleration right) { - return left._meterPerSecondSquared >= right._meterPerSecondSquared; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Acceleration left, Acceleration right) { - return left._meterPerSecondSquared < right._meterPerSecondSquared; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Acceleration left, Acceleration right) { - return left._meterPerSecondSquared > right._meterPerSecondSquared; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Acceleration left, Acceleration right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._meterPerSecondSquared == right._meterPerSecondSquared; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Acceleration left, Acceleration right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._meterPerSecondSquared != right._meterPerSecondSquared; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -904,7 +787,7 @@ public override bool Equals(object obj) return false; } - return _meterPerSecondSquared.Equals(((Acceleration) obj)._meterPerSecondSquared); + return AsBaseUnitMeterPerSecondSquared().Equals(((Acceleration) obj).AsBaseUnitMeterPerSecondSquared()); } /// @@ -917,12 +800,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Acceleration other, Acceleration maxError) { - return Math.Abs(_meterPerSecondSquared - other._meterPerSecondSquared) <= maxError._meterPerSecondSquared; + return Math.Abs(AsBaseUnitMeterPerSecondSquared() - other.AsBaseUnitMeterPerSecondSquared()) <= maxError.AsBaseUnitMeterPerSecondSquared(); } public override int GetHashCode() { - return _meterPerSecondSquared.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -932,38 +815,31 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(AccelerationUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitMeterPerSecondSquared(); + switch (unit) { - case AccelerationUnit.CentimeterPerSecondSquared: - return CentimeterPerSecondSquared; - case AccelerationUnit.DecimeterPerSecondSquared: - return DecimeterPerSecondSquared; - case AccelerationUnit.FootPerSecondSquared: - return FeetPerSecondSquared; - case AccelerationUnit.InchPerSecondSquared: - return InchesPerSecondSquared; - case AccelerationUnit.KilometerPerSecondSquared: - return KilometerPerSecondSquared; - case AccelerationUnit.KnotPerHour: - return KnotsPerHour; - case AccelerationUnit.KnotPerMinute: - return KnotsPerMinute; - case AccelerationUnit.KnotPerSecond: - return KnotsPerSecond; - case AccelerationUnit.MeterPerSecondSquared: - return MeterPerSecondSquared; - case AccelerationUnit.MicrometerPerSecondSquared: - return MicrometerPerSecondSquared; - case AccelerationUnit.MillimeterPerSecondSquared: - return MillimeterPerSecondSquared; - case AccelerationUnit.NanometerPerSecondSquared: - return NanometerPerSecondSquared; - case AccelerationUnit.StandardGravity: - return StandardGravity; + case AccelerationUnit.CentimeterPerSecondSquared: return (baseUnitValue) / 1e-2d; + case AccelerationUnit.DecimeterPerSecondSquared: return (baseUnitValue) / 1e-1d; + case AccelerationUnit.FootPerSecondSquared: return baseUnitValue/0.304800; + case AccelerationUnit.InchPerSecondSquared: return baseUnitValue/0.0254; + case AccelerationUnit.KilometerPerSecondSquared: return (baseUnitValue) / 1e3d; + case AccelerationUnit.KnotPerHour: return baseUnitValue/0.5144444444444*3600; + case AccelerationUnit.KnotPerMinute: return baseUnitValue/0.5144444444444*60; + case AccelerationUnit.KnotPerSecond: return baseUnitValue/0.5144444444444; + case AccelerationUnit.MeterPerSecondSquared: return baseUnitValue; + case AccelerationUnit.MicrometerPerSecondSquared: return (baseUnitValue) / 1e-6d; + case AccelerationUnit.MillimeterPerSecondSquared: return (baseUnitValue) / 1e-3d; + case AccelerationUnit.NanometerPerSecondSquared: return (baseUnitValue) / 1e-9d; + case AccelerationUnit.StandardGravity: return baseUnitValue/9.80665; default: throw new NotImplementedException("unit: " + unit); @@ -1005,7 +881,11 @@ public static Acceleration Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1024,17 +904,24 @@ public static Acceleration Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Acceleration Parse(string str, [CanBeNull] Culture culture) + public static Acceleration Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1060,16 +947,41 @@ public static bool TryParse([CanBeNull] string str, out Acceleration result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Acceleration result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Acceleration result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1082,6 +994,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1095,11 +1008,14 @@ public static AccelerationUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static AccelerationUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1108,6 +1024,8 @@ public static AccelerationUnit ParseUnit(string str, [CanBeNull] string cultureN /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1120,18 +1038,18 @@ public static AccelerationUnit ParseUnit(string str, [CanBeNull] string cultureN #else public #endif - static AccelerationUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static AccelerationUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == AccelerationUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AccelerationUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1140,6 +1058,7 @@ static AccelerationUnit ParseUnit(string str, IFormatProvider formatProvider = n #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is MeterPerSecondSquared /// @@ -1151,7 +1070,7 @@ static AccelerationUnit ParseUnit(string str, IFormatProvider formatProvider = n /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1168,74 +1087,141 @@ public string ToString(AccelerationUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(AccelerationUnit unit, [CanBeNull] Culture culture) + public string ToString( + AccelerationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(AccelerationUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + AccelerationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(AccelerationUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + AccelerationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Acceleration /// - public static Acceleration MaxValue - { - get - { - return new Acceleration(double.MaxValue); - } - } + public static Acceleration MaxValue => new Acceleration(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Acceleration /// - public static Acceleration MinValue + public static Acceleration MinValue => new Acceleration(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitMeterPerSecondSquared() { - get + if (Unit == AccelerationUnit.MeterPerSecondSquared) { return _value; } + + switch (Unit) { - return new Acceleration(double.MinValue); - } - } - } + case AccelerationUnit.CentimeterPerSecondSquared: return (_value) * 1e-2d; + case AccelerationUnit.DecimeterPerSecondSquared: return (_value) * 1e-1d; + case AccelerationUnit.FootPerSecondSquared: return _value*0.304800; + case AccelerationUnit.InchPerSecondSquared: return _value*0.0254; + case AccelerationUnit.KilometerPerSecondSquared: return (_value) * 1e3d; + case AccelerationUnit.KnotPerHour: return _value*0.5144444444444/3600; + case AccelerationUnit.KnotPerMinute: return _value*0.5144444444444/60; + case AccelerationUnit.KnotPerSecond: return _value*0.5144444444444; + case AccelerationUnit.MeterPerSecondSquared: return _value; + case AccelerationUnit.MicrometerPerSecondSquared: return (_value) * 1e-6d; + case AccelerationUnit.MillimeterPerSecondSquared: return (_value) * 1e-3d; + case AccelerationUnit.NanometerPerSecondSquared: return (_value) * 1e-9d; + case AccelerationUnit.StandardGravity: return _value*9.80665; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(AccelerationUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs index 70e59054a6..97026163cc 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct AmountOfSubstance : IComparable, IComparable - /// Base unit of AmountOfSubstance. + /// The numeric value this quantity was constructed with. /// - private readonly double _moles; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AmountOfSubstanceUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public AmountOfSubstance() : this(0) + public AmountOfSubstance() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public AmountOfSubstance(double moles) { - _moles = Convert.ToDouble(moles); + _value = Convert.ToDouble(moles); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + AmountOfSubstance(double numericValue, AmountOfSubstanceUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Mole. + /// + /// Value assuming base unit Mole. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - AmountOfSubstance(long moles) - { - _moles = Convert.ToDouble(moles); - } + AmountOfSubstance(long moles) : this(Convert.ToDouble(moles), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Mole. + /// + /// Value assuming base unit Mole. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - AmountOfSubstance(decimal moles) - { - _moles = Convert.ToDouble(moles); - } + AmountOfSubstance(decimal moles) : this(Convert.ToDouble(moles), BaseUnit) { } #region Properties @@ -119,136 +156,74 @@ public AmountOfSubstance(double moles) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static AmountOfSubstanceUnit BaseUnit - { - get { return AmountOfSubstanceUnit.Mole; } - } + public static AmountOfSubstanceUnit BaseUnit => AmountOfSubstanceUnit.Mole; /// /// All units of measurement for the AmountOfSubstance quantity. /// public static AmountOfSubstanceUnit[] Units { get; } = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().ToArray(); - /// /// Get AmountOfSubstance in Centimoles. /// - public double Centimoles - { - get { return (_moles) / 1e-2d; } - } - + public double Centimoles => As(AmountOfSubstanceUnit.Centimole); /// /// Get AmountOfSubstance in CentipoundMoles. /// - public double CentipoundMoles - { - get { return (_moles/453.59237) / 1e-2d; } - } - + public double CentipoundMoles => As(AmountOfSubstanceUnit.CentipoundMole); /// /// Get AmountOfSubstance in Decimoles. /// - public double Decimoles - { - get { return (_moles) / 1e-1d; } - } - + public double Decimoles => As(AmountOfSubstanceUnit.Decimole); /// /// Get AmountOfSubstance in DecipoundMoles. /// - public double DecipoundMoles - { - get { return (_moles/453.59237) / 1e-1d; } - } - + public double DecipoundMoles => As(AmountOfSubstanceUnit.DecipoundMole); /// /// Get AmountOfSubstance in Kilomoles. /// - public double Kilomoles - { - get { return (_moles) / 1e3d; } - } - + public double Kilomoles => As(AmountOfSubstanceUnit.Kilomole); /// /// Get AmountOfSubstance in KilopoundMoles. /// - public double KilopoundMoles - { - get { return (_moles/453.59237) / 1e3d; } - } - + public double KilopoundMoles => As(AmountOfSubstanceUnit.KilopoundMole); /// /// Get AmountOfSubstance in Micromoles. /// - public double Micromoles - { - get { return (_moles) / 1e-6d; } - } - + public double Micromoles => As(AmountOfSubstanceUnit.Micromole); /// /// Get AmountOfSubstance in MicropoundMoles. /// - public double MicropoundMoles - { - get { return (_moles/453.59237) / 1e-6d; } - } - + public double MicropoundMoles => As(AmountOfSubstanceUnit.MicropoundMole); /// /// Get AmountOfSubstance in Millimoles. /// - public double Millimoles - { - get { return (_moles) / 1e-3d; } - } - + public double Millimoles => As(AmountOfSubstanceUnit.Millimole); /// /// Get AmountOfSubstance in MillipoundMoles. /// - public double MillipoundMoles - { - get { return (_moles/453.59237) / 1e-3d; } - } - + public double MillipoundMoles => As(AmountOfSubstanceUnit.MillipoundMole); /// /// Get AmountOfSubstance in Moles. /// - public double Moles - { - get { return _moles; } - } - + public double Moles => As(AmountOfSubstanceUnit.Mole); /// /// Get AmountOfSubstance in Nanomoles. /// - public double Nanomoles - { - get { return (_moles) / 1e-9d; } - } - + public double Nanomoles => As(AmountOfSubstanceUnit.Nanomole); /// /// Get AmountOfSubstance in NanopoundMoles. /// - public double NanopoundMoles - { - get { return (_moles/453.59237) / 1e-9d; } - } - + public double NanopoundMoles => As(AmountOfSubstanceUnit.NanopoundMole); /// /// Get AmountOfSubstance in PoundMoles. /// - public double PoundMoles - { - get { return _moles/453.59237; } - } + public double PoundMoles => As(AmountOfSubstanceUnit.PoundMole); #endregion #region Static - public static AmountOfSubstance Zero - { - get { return new AmountOfSubstance(); } - } + public static AmountOfSubstance Zero => new AmountOfSubstance(0, BaseUnit); /// /// Get AmountOfSubstance from Centimoles. @@ -256,17 +231,13 @@ public static AmountOfSubstance Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromCentimoles(double centimoles) - { - double value = (double) centimoles; - return new AmountOfSubstance((value) * 1e-2d); - } #else public static AmountOfSubstance FromCentimoles(QuantityValue centimoles) +#endif { double value = (double) centimoles; - return new AmountOfSubstance(((value) * 1e-2d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); } -#endif /// /// Get AmountOfSubstance from CentipoundMoles. @@ -274,17 +245,13 @@ public static AmountOfSubstance FromCentimoles(QuantityValue centimoles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromCentipoundMoles(double centipoundmoles) - { - double value = (double) centipoundmoles; - return new AmountOfSubstance((value*453.59237) * 1e-2d); - } #else public static AmountOfSubstance FromCentipoundMoles(QuantityValue centipoundmoles) +#endif { double value = (double) centipoundmoles; - return new AmountOfSubstance(((value*453.59237) * 1e-2d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); } -#endif /// /// Get AmountOfSubstance from Decimoles. @@ -292,17 +259,13 @@ public static AmountOfSubstance FromCentipoundMoles(QuantityValue centipoundmole #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromDecimoles(double decimoles) - { - double value = (double) decimoles; - return new AmountOfSubstance((value) * 1e-1d); - } #else public static AmountOfSubstance FromDecimoles(QuantityValue decimoles) +#endif { double value = (double) decimoles; - return new AmountOfSubstance(((value) * 1e-1d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); } -#endif /// /// Get AmountOfSubstance from DecipoundMoles. @@ -310,17 +273,13 @@ public static AmountOfSubstance FromDecimoles(QuantityValue decimoles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromDecipoundMoles(double decipoundmoles) - { - double value = (double) decipoundmoles; - return new AmountOfSubstance((value*453.59237) * 1e-1d); - } #else public static AmountOfSubstance FromDecipoundMoles(QuantityValue decipoundmoles) +#endif { double value = (double) decipoundmoles; - return new AmountOfSubstance(((value*453.59237) * 1e-1d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); } -#endif /// /// Get AmountOfSubstance from Kilomoles. @@ -328,17 +287,13 @@ public static AmountOfSubstance FromDecipoundMoles(QuantityValue decipoundmoles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromKilomoles(double kilomoles) - { - double value = (double) kilomoles; - return new AmountOfSubstance((value) * 1e3d); - } #else public static AmountOfSubstance FromKilomoles(QuantityValue kilomoles) +#endif { double value = (double) kilomoles; - return new AmountOfSubstance(((value) * 1e3d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); } -#endif /// /// Get AmountOfSubstance from KilopoundMoles. @@ -346,17 +301,13 @@ public static AmountOfSubstance FromKilomoles(QuantityValue kilomoles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromKilopoundMoles(double kilopoundmoles) - { - double value = (double) kilopoundmoles; - return new AmountOfSubstance((value*453.59237) * 1e3d); - } #else public static AmountOfSubstance FromKilopoundMoles(QuantityValue kilopoundmoles) +#endif { double value = (double) kilopoundmoles; - return new AmountOfSubstance(((value*453.59237) * 1e3d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); } -#endif /// /// Get AmountOfSubstance from Micromoles. @@ -364,17 +315,13 @@ public static AmountOfSubstance FromKilopoundMoles(QuantityValue kilopoundmoles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromMicromoles(double micromoles) - { - double value = (double) micromoles; - return new AmountOfSubstance((value) * 1e-6d); - } #else public static AmountOfSubstance FromMicromoles(QuantityValue micromoles) +#endif { double value = (double) micromoles; - return new AmountOfSubstance(((value) * 1e-6d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); } -#endif /// /// Get AmountOfSubstance from MicropoundMoles. @@ -382,17 +329,13 @@ public static AmountOfSubstance FromMicromoles(QuantityValue micromoles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromMicropoundMoles(double micropoundmoles) - { - double value = (double) micropoundmoles; - return new AmountOfSubstance((value*453.59237) * 1e-6d); - } #else public static AmountOfSubstance FromMicropoundMoles(QuantityValue micropoundmoles) +#endif { double value = (double) micropoundmoles; - return new AmountOfSubstance(((value*453.59237) * 1e-6d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); } -#endif /// /// Get AmountOfSubstance from Millimoles. @@ -400,17 +343,13 @@ public static AmountOfSubstance FromMicropoundMoles(QuantityValue micropoundmole #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromMillimoles(double millimoles) - { - double value = (double) millimoles; - return new AmountOfSubstance((value) * 1e-3d); - } #else public static AmountOfSubstance FromMillimoles(QuantityValue millimoles) +#endif { double value = (double) millimoles; - return new AmountOfSubstance(((value) * 1e-3d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); } -#endif /// /// Get AmountOfSubstance from MillipoundMoles. @@ -418,17 +357,13 @@ public static AmountOfSubstance FromMillimoles(QuantityValue millimoles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromMillipoundMoles(double millipoundmoles) - { - double value = (double) millipoundmoles; - return new AmountOfSubstance((value*453.59237) * 1e-3d); - } #else public static AmountOfSubstance FromMillipoundMoles(QuantityValue millipoundmoles) +#endif { double value = (double) millipoundmoles; - return new AmountOfSubstance(((value*453.59237) * 1e-3d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); } -#endif /// /// Get AmountOfSubstance from Moles. @@ -436,17 +371,13 @@ public static AmountOfSubstance FromMillipoundMoles(QuantityValue millipoundmole #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromMoles(double moles) - { - double value = (double) moles; - return new AmountOfSubstance(value); - } #else public static AmountOfSubstance FromMoles(QuantityValue moles) +#endif { double value = (double) moles; - return new AmountOfSubstance((value)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); } -#endif /// /// Get AmountOfSubstance from Nanomoles. @@ -454,17 +385,13 @@ public static AmountOfSubstance FromMoles(QuantityValue moles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromNanomoles(double nanomoles) - { - double value = (double) nanomoles; - return new AmountOfSubstance((value) * 1e-9d); - } #else public static AmountOfSubstance FromNanomoles(QuantityValue nanomoles) +#endif { double value = (double) nanomoles; - return new AmountOfSubstance(((value) * 1e-9d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); } -#endif /// /// Get AmountOfSubstance from NanopoundMoles. @@ -472,17 +399,13 @@ public static AmountOfSubstance FromNanomoles(QuantityValue nanomoles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromNanopoundMoles(double nanopoundmoles) - { - double value = (double) nanopoundmoles; - return new AmountOfSubstance((value*453.59237) * 1e-9d); - } #else public static AmountOfSubstance FromNanopoundMoles(QuantityValue nanopoundmoles) +#endif { double value = (double) nanopoundmoles; - return new AmountOfSubstance(((value*453.59237) * 1e-9d)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); } -#endif /// /// Get AmountOfSubstance from PoundMoles. @@ -490,17 +413,13 @@ public static AmountOfSubstance FromNanopoundMoles(QuantityValue nanopoundmoles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmountOfSubstance FromPoundMoles(double poundmoles) - { - double value = (double) poundmoles; - return new AmountOfSubstance(value*453.59237); - } #else public static AmountOfSubstance FromPoundMoles(QuantityValue poundmoles) +#endif { double value = (double) poundmoles; - return new AmountOfSubstance((value*453.59237)); + return new AmountOfSubstance(value, AmountOfSubstanceUnit.PoundMole); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -730,40 +649,7 @@ public static AmountOfSubstance From(double value, AmountOfSubstanceUnit fromUni public static AmountOfSubstance From(QuantityValue value, AmountOfSubstanceUnit fromUnit) #endif { - switch (fromUnit) - { - case AmountOfSubstanceUnit.Centimole: - return FromCentimoles(value); - case AmountOfSubstanceUnit.CentipoundMole: - return FromCentipoundMoles(value); - case AmountOfSubstanceUnit.Decimole: - return FromDecimoles(value); - case AmountOfSubstanceUnit.DecipoundMole: - return FromDecipoundMoles(value); - case AmountOfSubstanceUnit.Kilomole: - return FromKilomoles(value); - case AmountOfSubstanceUnit.KilopoundMole: - return FromKilopoundMoles(value); - case AmountOfSubstanceUnit.Micromole: - return FromMicromoles(value); - case AmountOfSubstanceUnit.MicropoundMole: - return FromMicropoundMoles(value); - case AmountOfSubstanceUnit.Millimole: - return FromMillimoles(value); - case AmountOfSubstanceUnit.MillipoundMole: - return FromMillipoundMoles(value); - case AmountOfSubstanceUnit.Mole: - return FromMoles(value); - case AmountOfSubstanceUnit.Nanomole: - return FromNanomoles(value); - case AmountOfSubstanceUnit.NanopoundMole: - return FromNanopoundMoles(value); - case AmountOfSubstanceUnit.PoundMole: - return FromPoundMoles(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new AmountOfSubstance((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -780,40 +666,8 @@ public static AmountOfSubstance From(QuantityValue value, AmountOfSubstanceUnit { return null; } - switch (fromUnit) - { - case AmountOfSubstanceUnit.Centimole: - return FromCentimoles(value.Value); - case AmountOfSubstanceUnit.CentipoundMole: - return FromCentipoundMoles(value.Value); - case AmountOfSubstanceUnit.Decimole: - return FromDecimoles(value.Value); - case AmountOfSubstanceUnit.DecipoundMole: - return FromDecipoundMoles(value.Value); - case AmountOfSubstanceUnit.Kilomole: - return FromKilomoles(value.Value); - case AmountOfSubstanceUnit.KilopoundMole: - return FromKilopoundMoles(value.Value); - case AmountOfSubstanceUnit.Micromole: - return FromMicromoles(value.Value); - case AmountOfSubstanceUnit.MicropoundMole: - return FromMicropoundMoles(value.Value); - case AmountOfSubstanceUnit.Millimole: - return FromMillimoles(value.Value); - case AmountOfSubstanceUnit.MillipoundMole: - return FromMillipoundMoles(value.Value); - case AmountOfSubstanceUnit.Mole: - return FromMoles(value.Value); - case AmountOfSubstanceUnit.Nanomole: - return FromNanomoles(value.Value); - case AmountOfSubstanceUnit.NanopoundMole: - return FromNanopoundMoles(value.Value); - case AmountOfSubstanceUnit.PoundMole: - return FromPoundMoles(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new AmountOfSubstance((double)value.Value, fromUnit); } #endif @@ -832,12 +686,29 @@ public static string GetAbbreviation(AmountOfSubstanceUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(AmountOfSubstanceUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + AmountOfSubstanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -848,37 +719,37 @@ public static string GetAbbreviation(AmountOfSubstanceUnit unit, [CanBeNull] Cul #if !WINDOWS_UWP public static AmountOfSubstance operator -(AmountOfSubstance right) { - return new AmountOfSubstance(-right._moles); + return new AmountOfSubstance(-right.Value, right.Unit); } public static AmountOfSubstance operator +(AmountOfSubstance left, AmountOfSubstance right) { - return new AmountOfSubstance(left._moles + right._moles); + return new AmountOfSubstance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static AmountOfSubstance operator -(AmountOfSubstance left, AmountOfSubstance right) { - return new AmountOfSubstance(left._moles - right._moles); + return new AmountOfSubstance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static AmountOfSubstance operator *(double left, AmountOfSubstance right) { - return new AmountOfSubstance(left*right._moles); + return new AmountOfSubstance(left * right.Value, right.Unit); } public static AmountOfSubstance operator *(AmountOfSubstance left, double right) { - return new AmountOfSubstance(left._moles*(double)right); + return new AmountOfSubstance(left.Value * right, left.Unit); } public static AmountOfSubstance operator /(AmountOfSubstance left, double right) { - return new AmountOfSubstance(left._moles/(double)right); + return new AmountOfSubstance(left.Value / right, left.Unit); } public static double operator /(AmountOfSubstance left, AmountOfSubstance right) { - return Convert.ToDouble(left._moles/right._moles); + return left.Moles / right.Moles; } #endif @@ -901,43 +772,43 @@ public int CompareTo(object obj) #endif int CompareTo(AmountOfSubstance other) { - return _moles.CompareTo(other._moles); + return AsBaseUnitMoles().CompareTo(other.AsBaseUnitMoles()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(AmountOfSubstance left, AmountOfSubstance right) { - return left._moles <= right._moles; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(AmountOfSubstance left, AmountOfSubstance right) { - return left._moles >= right._moles; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(AmountOfSubstance left, AmountOfSubstance right) { - return left._moles < right._moles; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(AmountOfSubstance left, AmountOfSubstance right) { - return left._moles > right._moles; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(AmountOfSubstance left, AmountOfSubstance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._moles == right._moles; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(AmountOfSubstance left, AmountOfSubstance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._moles != right._moles; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -949,7 +820,7 @@ public override bool Equals(object obj) return false; } - return _moles.Equals(((AmountOfSubstance) obj)._moles); + return AsBaseUnitMoles().Equals(((AmountOfSubstance) obj).AsBaseUnitMoles()); } /// @@ -962,12 +833,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(AmountOfSubstance other, AmountOfSubstance maxError) { - return Math.Abs(_moles - other._moles) <= maxError._moles; + return Math.Abs(AsBaseUnitMoles() - other.AsBaseUnitMoles()) <= maxError.AsBaseUnitMoles(); } public override int GetHashCode() { - return _moles.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -977,40 +848,32 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(AmountOfSubstanceUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitMoles(); + switch (unit) { - case AmountOfSubstanceUnit.Centimole: - return Centimoles; - case AmountOfSubstanceUnit.CentipoundMole: - return CentipoundMoles; - case AmountOfSubstanceUnit.Decimole: - return Decimoles; - case AmountOfSubstanceUnit.DecipoundMole: - return DecipoundMoles; - case AmountOfSubstanceUnit.Kilomole: - return Kilomoles; - case AmountOfSubstanceUnit.KilopoundMole: - return KilopoundMoles; - case AmountOfSubstanceUnit.Micromole: - return Micromoles; - case AmountOfSubstanceUnit.MicropoundMole: - return MicropoundMoles; - case AmountOfSubstanceUnit.Millimole: - return Millimoles; - case AmountOfSubstanceUnit.MillipoundMole: - return MillipoundMoles; - case AmountOfSubstanceUnit.Mole: - return Moles; - case AmountOfSubstanceUnit.Nanomole: - return Nanomoles; - case AmountOfSubstanceUnit.NanopoundMole: - return NanopoundMoles; - case AmountOfSubstanceUnit.PoundMole: - return PoundMoles; + case AmountOfSubstanceUnit.Centimole: return (baseUnitValue) / 1e-2d; + case AmountOfSubstanceUnit.CentipoundMole: return (baseUnitValue/453.59237) / 1e-2d; + case AmountOfSubstanceUnit.Decimole: return (baseUnitValue) / 1e-1d; + case AmountOfSubstanceUnit.DecipoundMole: return (baseUnitValue/453.59237) / 1e-1d; + case AmountOfSubstanceUnit.Kilomole: return (baseUnitValue) / 1e3d; + case AmountOfSubstanceUnit.KilopoundMole: return (baseUnitValue/453.59237) / 1e3d; + case AmountOfSubstanceUnit.Micromole: return (baseUnitValue) / 1e-6d; + case AmountOfSubstanceUnit.MicropoundMole: return (baseUnitValue/453.59237) / 1e-6d; + case AmountOfSubstanceUnit.Millimole: return (baseUnitValue) / 1e-3d; + case AmountOfSubstanceUnit.MillipoundMole: return (baseUnitValue/453.59237) / 1e-3d; + case AmountOfSubstanceUnit.Mole: return baseUnitValue; + case AmountOfSubstanceUnit.Nanomole: return (baseUnitValue) / 1e-9d; + case AmountOfSubstanceUnit.NanopoundMole: return (baseUnitValue/453.59237) / 1e-9d; + case AmountOfSubstanceUnit.PoundMole: return baseUnitValue/453.59237; default: throw new NotImplementedException("unit: " + unit); @@ -1052,7 +915,11 @@ public static AmountOfSubstance Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1071,17 +938,24 @@ public static AmountOfSubstance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static AmountOfSubstance Parse(string str, [CanBeNull] Culture culture) + public static AmountOfSubstance Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1107,16 +981,41 @@ public static bool TryParse([CanBeNull] string str, out AmountOfSubstance result /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out AmountOfSubstance result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out AmountOfSubstance result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1129,6 +1028,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1142,11 +1042,14 @@ public static AmountOfSubstanceUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static AmountOfSubstanceUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1155,6 +1058,8 @@ public static AmountOfSubstanceUnit ParseUnit(string str, [CanBeNull] string cul /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1167,18 +1072,18 @@ public static AmountOfSubstanceUnit ParseUnit(string str, [CanBeNull] string cul #else public #endif - static AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == AmountOfSubstanceUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AmountOfSubstanceUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1187,6 +1092,7 @@ static AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider formatProvide #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Mole /// @@ -1198,7 +1104,7 @@ static AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider formatProvide /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1215,74 +1121,142 @@ public string ToString(AmountOfSubstanceUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(AmountOfSubstanceUnit unit, [CanBeNull] Culture culture) + public string ToString( + AmountOfSubstanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(AmountOfSubstanceUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + AmountOfSubstanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(AmountOfSubstanceUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + AmountOfSubstanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of AmountOfSubstance /// - public static AmountOfSubstance MaxValue - { - get - { - return new AmountOfSubstance(double.MaxValue); - } - } + public static AmountOfSubstance MaxValue => new AmountOfSubstance(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of AmountOfSubstance /// - public static AmountOfSubstance MinValue + public static AmountOfSubstance MinValue => new AmountOfSubstance(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitMoles() { - get + if (Unit == AmountOfSubstanceUnit.Mole) { return _value; } + + switch (Unit) { - return new AmountOfSubstance(double.MinValue); - } - } - } + case AmountOfSubstanceUnit.Centimole: return (_value) * 1e-2d; + case AmountOfSubstanceUnit.CentipoundMole: return (_value*453.59237) * 1e-2d; + case AmountOfSubstanceUnit.Decimole: return (_value) * 1e-1d; + case AmountOfSubstanceUnit.DecipoundMole: return (_value*453.59237) * 1e-1d; + case AmountOfSubstanceUnit.Kilomole: return (_value) * 1e3d; + case AmountOfSubstanceUnit.KilopoundMole: return (_value*453.59237) * 1e3d; + case AmountOfSubstanceUnit.Micromole: return (_value) * 1e-6d; + case AmountOfSubstanceUnit.MicropoundMole: return (_value*453.59237) * 1e-6d; + case AmountOfSubstanceUnit.Millimole: return (_value) * 1e-3d; + case AmountOfSubstanceUnit.MillipoundMole: return (_value*453.59237) * 1e-3d; + case AmountOfSubstanceUnit.Mole: return _value; + case AmountOfSubstanceUnit.Nanomole: return (_value) * 1e-9d; + case AmountOfSubstanceUnit.NanopoundMole: return (_value*453.59237) * 1e-9d; + case AmountOfSubstanceUnit.PoundMole: return _value*453.59237; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(AmountOfSubstanceUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs index 73a7de4b8b..1b8e2903ea 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct AmplitudeRatio : IComparable, IComparable #endif { /// - /// Base unit of AmplitudeRatio. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _decibelVolts; + private readonly AmplitudeRatioUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public AmplitudeRatio() : this(0) + public AmplitudeRatio() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public AmplitudeRatio(double decibelvolts) { - _decibelVolts = Convert.ToDouble(decibelvolts); + _value = Convert.ToDouble(decibelvolts); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + AmplitudeRatio(double numericValue, AmplitudeRatioUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit DecibelVolt. + /// + /// Value assuming base unit DecibelVolt. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - AmplitudeRatio(long decibelvolts) - { - _decibelVolts = Convert.ToDouble(decibelvolts); - } + AmplitudeRatio(long decibelvolts) : this(Convert.ToDouble(decibelvolts), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit DecibelVolt. + /// + /// Value assuming base unit DecibelVolt. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - AmplitudeRatio(decimal decibelvolts) - { - _decibelVolts = Convert.ToDouble(decibelvolts); - } + AmplitudeRatio(decimal decibelvolts) : this(Convert.ToDouble(decibelvolts), BaseUnit) { } #region Properties @@ -119,56 +156,34 @@ public AmplitudeRatio(double decibelvolts) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static AmplitudeRatioUnit BaseUnit - { - get { return AmplitudeRatioUnit.DecibelVolt; } - } + public static AmplitudeRatioUnit BaseUnit => AmplitudeRatioUnit.DecibelVolt; /// /// All units of measurement for the AmplitudeRatio quantity. /// public static AmplitudeRatioUnit[] Units { get; } = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().ToArray(); - /// /// Get AmplitudeRatio in DecibelMicrovolts. /// - public double DecibelMicrovolts - { - get { return _decibelVolts + 120; } - } - + public double DecibelMicrovolts => As(AmplitudeRatioUnit.DecibelMicrovolt); /// /// Get AmplitudeRatio in DecibelMillivolts. /// - public double DecibelMillivolts - { - get { return _decibelVolts + 60; } - } - + public double DecibelMillivolts => As(AmplitudeRatioUnit.DecibelMillivolt); /// /// Get AmplitudeRatio in DecibelsUnloaded. /// - public double DecibelsUnloaded - { - get { return _decibelVolts + 2.218487499; } - } - + public double DecibelsUnloaded => As(AmplitudeRatioUnit.DecibelUnloaded); /// /// Get AmplitudeRatio in DecibelVolts. /// - public double DecibelVolts - { - get { return _decibelVolts; } - } + public double DecibelVolts => As(AmplitudeRatioUnit.DecibelVolt); #endregion #region Static - public static AmplitudeRatio Zero - { - get { return new AmplitudeRatio(); } - } + public static AmplitudeRatio Zero => new AmplitudeRatio(0, BaseUnit); /// /// Get AmplitudeRatio from DecibelMicrovolts. @@ -176,17 +191,13 @@ public static AmplitudeRatio Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmplitudeRatio FromDecibelMicrovolts(double decibelmicrovolts) - { - double value = (double) decibelmicrovolts; - return new AmplitudeRatio(value - 120); - } #else public static AmplitudeRatio FromDecibelMicrovolts(QuantityValue decibelmicrovolts) +#endif { double value = (double) decibelmicrovolts; - return new AmplitudeRatio((value - 120)); + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); } -#endif /// /// Get AmplitudeRatio from DecibelMillivolts. @@ -194,17 +205,13 @@ public static AmplitudeRatio FromDecibelMicrovolts(QuantityValue decibelmicrovol #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmplitudeRatio FromDecibelMillivolts(double decibelmillivolts) - { - double value = (double) decibelmillivolts; - return new AmplitudeRatio(value - 60); - } #else public static AmplitudeRatio FromDecibelMillivolts(QuantityValue decibelmillivolts) +#endif { double value = (double) decibelmillivolts; - return new AmplitudeRatio((value - 60)); + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); } -#endif /// /// Get AmplitudeRatio from DecibelsUnloaded. @@ -212,17 +219,13 @@ public static AmplitudeRatio FromDecibelMillivolts(QuantityValue decibelmillivol #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmplitudeRatio FromDecibelsUnloaded(double decibelsunloaded) - { - double value = (double) decibelsunloaded; - return new AmplitudeRatio(value - 2.218487499); - } #else public static AmplitudeRatio FromDecibelsUnloaded(QuantityValue decibelsunloaded) +#endif { double value = (double) decibelsunloaded; - return new AmplitudeRatio((value - 2.218487499)); + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); } -#endif /// /// Get AmplitudeRatio from DecibelVolts. @@ -230,17 +233,13 @@ public static AmplitudeRatio FromDecibelsUnloaded(QuantityValue decibelsunloaded #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AmplitudeRatio FromDecibelVolts(double decibelvolts) - { - double value = (double) decibelvolts; - return new AmplitudeRatio(value); - } #else public static AmplitudeRatio FromDecibelVolts(QuantityValue decibelvolts) +#endif { double value = (double) decibelvolts; - return new AmplitudeRatio((value)); + return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelVolt); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -320,20 +319,7 @@ public static AmplitudeRatio From(double value, AmplitudeRatioUnit fromUnit) public static AmplitudeRatio From(QuantityValue value, AmplitudeRatioUnit fromUnit) #endif { - switch (fromUnit) - { - case AmplitudeRatioUnit.DecibelMicrovolt: - return FromDecibelMicrovolts(value); - case AmplitudeRatioUnit.DecibelMillivolt: - return FromDecibelMillivolts(value); - case AmplitudeRatioUnit.DecibelUnloaded: - return FromDecibelsUnloaded(value); - case AmplitudeRatioUnit.DecibelVolt: - return FromDecibelVolts(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new AmplitudeRatio((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -350,20 +336,8 @@ public static AmplitudeRatio From(QuantityValue value, AmplitudeRatioUnit fromUn { return null; } - switch (fromUnit) - { - case AmplitudeRatioUnit.DecibelMicrovolt: - return FromDecibelMicrovolts(value.Value); - case AmplitudeRatioUnit.DecibelMillivolt: - return FromDecibelMillivolts(value.Value); - case AmplitudeRatioUnit.DecibelUnloaded: - return FromDecibelsUnloaded(value.Value); - case AmplitudeRatioUnit.DecibelVolt: - return FromDecibelVolts(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new AmplitudeRatio((double)value.Value, fromUnit); } #endif @@ -382,12 +356,29 @@ public static string GetAbbreviation(AmplitudeRatioUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(AmplitudeRatioUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + AmplitudeRatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -398,45 +389,45 @@ public static string GetAbbreviation(AmplitudeRatioUnit unit, [CanBeNull] Cultur #if !WINDOWS_UWP public static AmplitudeRatio operator -(AmplitudeRatio right) { - return new AmplitudeRatio(-right._decibelVolts); + return new AmplitudeRatio(-right.Value, right.Unit); } 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._decibelVolts/20) + Math.Pow(10, right._decibelVolts/20))); + return new AmplitudeRatio(20*Math.Log10(Math.Pow(10, left.Value/20) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/20)), left.Unit); } 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._decibelVolts/20) - Math.Pow(10, right._decibelVolts/20))); + return new AmplitudeRatio(20*Math.Log10(Math.Pow(10, left.Value/20) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/20)), left.Unit); } public static AmplitudeRatio operator *(double left, AmplitudeRatio right) { // Logarithmic multiplication = addition - return new AmplitudeRatio(left + right._decibelVolts); + return new AmplitudeRatio(left + right.Value, right.Unit); } public static AmplitudeRatio operator *(AmplitudeRatio left, double right) { // Logarithmic multiplication = addition - return new AmplitudeRatio(left._decibelVolts + (double)right); + return new AmplitudeRatio(left.Value + (double)right, left.Unit); } public static AmplitudeRatio operator /(AmplitudeRatio left, double right) { // Logarithmic division = subtraction - return new AmplitudeRatio(left._decibelVolts - (double)right); + return new AmplitudeRatio(left.Value - (double)right, left.Unit); } public static double operator /(AmplitudeRatio left, AmplitudeRatio right) { // Logarithmic division = subtraction - return Convert.ToDouble(left._decibelVolts - right._decibelVolts); + return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); } #endif @@ -459,43 +450,43 @@ public int CompareTo(object obj) #endif int CompareTo(AmplitudeRatio other) { - return _decibelVolts.CompareTo(other._decibelVolts); + return AsBaseUnitDecibelVolts().CompareTo(other.AsBaseUnitDecibelVolts()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(AmplitudeRatio left, AmplitudeRatio right) { - return left._decibelVolts <= right._decibelVolts; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(AmplitudeRatio left, AmplitudeRatio right) { - return left._decibelVolts >= right._decibelVolts; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(AmplitudeRatio left, AmplitudeRatio right) { - return left._decibelVolts < right._decibelVolts; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(AmplitudeRatio left, AmplitudeRatio right) { - return left._decibelVolts > right._decibelVolts; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(AmplitudeRatio left, AmplitudeRatio right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._decibelVolts == right._decibelVolts; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(AmplitudeRatio left, AmplitudeRatio right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._decibelVolts != right._decibelVolts; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -507,7 +498,7 @@ public override bool Equals(object obj) return false; } - return _decibelVolts.Equals(((AmplitudeRatio) obj)._decibelVolts); + return AsBaseUnitDecibelVolts().Equals(((AmplitudeRatio) obj).AsBaseUnitDecibelVolts()); } /// @@ -520,12 +511,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(AmplitudeRatio other, AmplitudeRatio maxError) { - return Math.Abs(_decibelVolts - other._decibelVolts) <= maxError._decibelVolts; + return Math.Abs(AsBaseUnitDecibelVolts() - other.AsBaseUnitDecibelVolts()) <= maxError.AsBaseUnitDecibelVolts(); } public override int GetHashCode() { - return _decibelVolts.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -535,20 +526,22 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(AmplitudeRatioUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitDecibelVolts(); + switch (unit) { - case AmplitudeRatioUnit.DecibelMicrovolt: - return DecibelMicrovolts; - case AmplitudeRatioUnit.DecibelMillivolt: - return DecibelMillivolts; - case AmplitudeRatioUnit.DecibelUnloaded: - return DecibelsUnloaded; - case AmplitudeRatioUnit.DecibelVolt: - return DecibelVolts; + case AmplitudeRatioUnit.DecibelMicrovolt: return baseUnitValue + 120; + case AmplitudeRatioUnit.DecibelMillivolt: return baseUnitValue + 60; + case AmplitudeRatioUnit.DecibelUnloaded: return baseUnitValue + 2.218487499; + case AmplitudeRatioUnit.DecibelVolt: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -590,7 +583,11 @@ public static AmplitudeRatio Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -609,17 +606,24 @@ public static AmplitudeRatio Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static AmplitudeRatio Parse(string str, [CanBeNull] Culture culture) + public static AmplitudeRatio Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -645,16 +649,41 @@ public static bool TryParse([CanBeNull] string str, out AmplitudeRatio result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out AmplitudeRatio result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out AmplitudeRatio result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -667,6 +696,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -680,11 +710,14 @@ public static AmplitudeRatioUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static AmplitudeRatioUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -693,6 +726,8 @@ public static AmplitudeRatioUnit ParseUnit(string str, [CanBeNull] string cultur /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -705,18 +740,18 @@ public static AmplitudeRatioUnit ParseUnit(string str, [CanBeNull] string cultur #else public #endif - static AmplitudeRatioUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static AmplitudeRatioUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == AmplitudeRatioUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AmplitudeRatioUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -725,6 +760,7 @@ static AmplitudeRatioUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is DecibelVolt /// @@ -736,7 +772,7 @@ static AmplitudeRatioUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -753,74 +789,132 @@ public string ToString(AmplitudeRatioUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(AmplitudeRatioUnit unit, [CanBeNull] Culture culture) + public string ToString( + AmplitudeRatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(AmplitudeRatioUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + AmplitudeRatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(AmplitudeRatioUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + AmplitudeRatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of AmplitudeRatio /// - public static AmplitudeRatio MaxValue - { - get - { - return new AmplitudeRatio(double.MaxValue); - } - } + public static AmplitudeRatio MaxValue => new AmplitudeRatio(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of AmplitudeRatio /// - public static AmplitudeRatio MinValue + public static AmplitudeRatio MinValue => new AmplitudeRatio(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitDecibelVolts() { - get + if (Unit == AmplitudeRatioUnit.DecibelVolt) { return _value; } + + switch (Unit) { - return new AmplitudeRatio(double.MinValue); - } - } - } + case AmplitudeRatioUnit.DecibelMicrovolt: return _value - 120; + case AmplitudeRatioUnit.DecibelMillivolt: return _value - 60; + case AmplitudeRatioUnit.DecibelUnloaded: return _value - 2.218487499; + case AmplitudeRatioUnit.DecibelVolt: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(AmplitudeRatioUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs index ee99686cbf..59a3b874eb 100644 --- a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Angle : IComparable, IComparable #endif { /// - /// Base unit of Angle. + /// The numeric value this quantity was constructed with. /// - private readonly double _degrees; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AngleUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Angle() : this(0) + public Angle() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Angle(double degrees) { - _degrees = Convert.ToDouble(degrees); + _value = Convert.ToDouble(degrees); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Angle(double numericValue, AngleUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Degree. + /// + /// Value assuming base unit Degree. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Angle(long degrees) - { - _degrees = Convert.ToDouble(degrees); - } + Angle(long degrees) : this(Convert.ToDouble(degrees), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Degree. + /// + /// Value assuming base unit Degree. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Angle(decimal degrees) - { - _degrees = Convert.ToDouble(degrees); - } + Angle(decimal degrees) : this(Convert.ToDouble(degrees), BaseUnit) { } #region Properties @@ -119,136 +156,74 @@ public Angle(double degrees) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static AngleUnit BaseUnit - { - get { return AngleUnit.Degree; } - } + public static AngleUnit BaseUnit => AngleUnit.Degree; /// /// All units of measurement for the Angle quantity. /// public static AngleUnit[] Units { get; } = Enum.GetValues(typeof(AngleUnit)).Cast().ToArray(); - /// /// Get Angle in Arcminutes. /// - public double Arcminutes - { - get { return _degrees*60; } - } - + public double Arcminutes => As(AngleUnit.Arcminute); /// /// Get Angle in Arcseconds. /// - public double Arcseconds - { - get { return _degrees*3600; } - } - + public double Arcseconds => As(AngleUnit.Arcsecond); /// /// Get Angle in Centiradians. /// - public double Centiradians - { - get { return (_degrees/180*Math.PI) / 1e-2d; } - } - + public double Centiradians => As(AngleUnit.Centiradian); /// /// Get Angle in Deciradians. /// - public double Deciradians - { - get { return (_degrees/180*Math.PI) / 1e-1d; } - } - + public double Deciradians => As(AngleUnit.Deciradian); /// /// Get Angle in Degrees. /// - public double Degrees - { - get { return _degrees; } - } - + public double Degrees => As(AngleUnit.Degree); /// /// Get Angle in Gradians. /// - public double Gradians - { - get { return _degrees/0.9; } - } - + public double Gradians => As(AngleUnit.Gradian); /// /// Get Angle in Microdegrees. /// - public double Microdegrees - { - get { return (_degrees) / 1e-6d; } - } - + public double Microdegrees => As(AngleUnit.Microdegree); /// /// Get Angle in Microradians. /// - public double Microradians - { - get { return (_degrees/180*Math.PI) / 1e-6d; } - } - + public double Microradians => As(AngleUnit.Microradian); /// /// Get Angle in Millidegrees. /// - public double Millidegrees - { - get { return (_degrees) / 1e-3d; } - } - + public double Millidegrees => As(AngleUnit.Millidegree); /// /// Get Angle in Milliradians. /// - public double Milliradians - { - get { return (_degrees/180*Math.PI) / 1e-3d; } - } - + public double Milliradians => As(AngleUnit.Milliradian); /// /// Get Angle in Nanodegrees. /// - public double Nanodegrees - { - get { return (_degrees) / 1e-9d; } - } - + public double Nanodegrees => As(AngleUnit.Nanodegree); /// /// Get Angle in Nanoradians. /// - public double Nanoradians - { - get { return (_degrees/180*Math.PI) / 1e-9d; } - } - + public double Nanoradians => As(AngleUnit.Nanoradian); /// /// Get Angle in Radians. /// - public double Radians - { - get { return _degrees/180*Math.PI; } - } - + public double Radians => As(AngleUnit.Radian); /// /// Get Angle in Revolutions. /// - public double Revolutions - { - get { return _degrees/360; } - } + public double Revolutions => As(AngleUnit.Revolution); #endregion #region Static - public static Angle Zero - { - get { return new Angle(); } - } + public static Angle Zero => new Angle(0, BaseUnit); /// /// Get Angle from Arcminutes. @@ -256,17 +231,13 @@ public static Angle Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromArcminutes(double arcminutes) - { - double value = (double) arcminutes; - return new Angle(value/60); - } #else public static Angle FromArcminutes(QuantityValue arcminutes) +#endif { double value = (double) arcminutes; - return new Angle((value/60)); + return new Angle(value, AngleUnit.Arcminute); } -#endif /// /// Get Angle from Arcseconds. @@ -274,17 +245,13 @@ public static Angle FromArcminutes(QuantityValue arcminutes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromArcseconds(double arcseconds) - { - double value = (double) arcseconds; - return new Angle(value/3600); - } #else public static Angle FromArcseconds(QuantityValue arcseconds) +#endif { double value = (double) arcseconds; - return new Angle((value/3600)); + return new Angle(value, AngleUnit.Arcsecond); } -#endif /// /// Get Angle from Centiradians. @@ -292,17 +259,13 @@ public static Angle FromArcseconds(QuantityValue arcseconds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromCentiradians(double centiradians) - { - double value = (double) centiradians; - return new Angle((value*180/Math.PI) * 1e-2d); - } #else public static Angle FromCentiradians(QuantityValue centiradians) +#endif { double value = (double) centiradians; - return new Angle(((value*180/Math.PI) * 1e-2d)); + return new Angle(value, AngleUnit.Centiradian); } -#endif /// /// Get Angle from Deciradians. @@ -310,17 +273,13 @@ public static Angle FromCentiradians(QuantityValue centiradians) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromDeciradians(double deciradians) - { - double value = (double) deciradians; - return new Angle((value*180/Math.PI) * 1e-1d); - } #else public static Angle FromDeciradians(QuantityValue deciradians) +#endif { double value = (double) deciradians; - return new Angle(((value*180/Math.PI) * 1e-1d)); + return new Angle(value, AngleUnit.Deciradian); } -#endif /// /// Get Angle from Degrees. @@ -328,17 +287,13 @@ public static Angle FromDeciradians(QuantityValue deciradians) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromDegrees(double degrees) - { - double value = (double) degrees; - return new Angle(value); - } #else public static Angle FromDegrees(QuantityValue degrees) +#endif { double value = (double) degrees; - return new Angle((value)); + return new Angle(value, AngleUnit.Degree); } -#endif /// /// Get Angle from Gradians. @@ -346,17 +301,13 @@ public static Angle FromDegrees(QuantityValue degrees) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromGradians(double gradians) - { - double value = (double) gradians; - return new Angle(value*0.9); - } #else public static Angle FromGradians(QuantityValue gradians) +#endif { double value = (double) gradians; - return new Angle((value*0.9)); + return new Angle(value, AngleUnit.Gradian); } -#endif /// /// Get Angle from Microdegrees. @@ -364,17 +315,13 @@ public static Angle FromGradians(QuantityValue gradians) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromMicrodegrees(double microdegrees) - { - double value = (double) microdegrees; - return new Angle((value) * 1e-6d); - } #else public static Angle FromMicrodegrees(QuantityValue microdegrees) +#endif { double value = (double) microdegrees; - return new Angle(((value) * 1e-6d)); + return new Angle(value, AngleUnit.Microdegree); } -#endif /// /// Get Angle from Microradians. @@ -382,17 +329,13 @@ public static Angle FromMicrodegrees(QuantityValue microdegrees) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromMicroradians(double microradians) - { - double value = (double) microradians; - return new Angle((value*180/Math.PI) * 1e-6d); - } #else public static Angle FromMicroradians(QuantityValue microradians) +#endif { double value = (double) microradians; - return new Angle(((value*180/Math.PI) * 1e-6d)); + return new Angle(value, AngleUnit.Microradian); } -#endif /// /// Get Angle from Millidegrees. @@ -400,17 +343,13 @@ public static Angle FromMicroradians(QuantityValue microradians) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromMillidegrees(double millidegrees) - { - double value = (double) millidegrees; - return new Angle((value) * 1e-3d); - } #else public static Angle FromMillidegrees(QuantityValue millidegrees) +#endif { double value = (double) millidegrees; - return new Angle(((value) * 1e-3d)); + return new Angle(value, AngleUnit.Millidegree); } -#endif /// /// Get Angle from Milliradians. @@ -418,17 +357,13 @@ public static Angle FromMillidegrees(QuantityValue millidegrees) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromMilliradians(double milliradians) - { - double value = (double) milliradians; - return new Angle((value*180/Math.PI) * 1e-3d); - } #else public static Angle FromMilliradians(QuantityValue milliradians) +#endif { double value = (double) milliradians; - return new Angle(((value*180/Math.PI) * 1e-3d)); + return new Angle(value, AngleUnit.Milliradian); } -#endif /// /// Get Angle from Nanodegrees. @@ -436,17 +371,13 @@ public static Angle FromMilliradians(QuantityValue milliradians) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromNanodegrees(double nanodegrees) - { - double value = (double) nanodegrees; - return new Angle((value) * 1e-9d); - } #else public static Angle FromNanodegrees(QuantityValue nanodegrees) +#endif { double value = (double) nanodegrees; - return new Angle(((value) * 1e-9d)); + return new Angle(value, AngleUnit.Nanodegree); } -#endif /// /// Get Angle from Nanoradians. @@ -454,17 +385,13 @@ public static Angle FromNanodegrees(QuantityValue nanodegrees) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromNanoradians(double nanoradians) - { - double value = (double) nanoradians; - return new Angle((value*180/Math.PI) * 1e-9d); - } #else public static Angle FromNanoradians(QuantityValue nanoradians) +#endif { double value = (double) nanoradians; - return new Angle(((value*180/Math.PI) * 1e-9d)); + return new Angle(value, AngleUnit.Nanoradian); } -#endif /// /// Get Angle from Radians. @@ -472,17 +399,13 @@ public static Angle FromNanoradians(QuantityValue nanoradians) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromRadians(double radians) - { - double value = (double) radians; - return new Angle(value*180/Math.PI); - } #else public static Angle FromRadians(QuantityValue radians) +#endif { double value = (double) radians; - return new Angle((value*180/Math.PI)); + return new Angle(value, AngleUnit.Radian); } -#endif /// /// Get Angle from Revolutions. @@ -490,17 +413,13 @@ public static Angle FromRadians(QuantityValue radians) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Angle FromRevolutions(double revolutions) - { - double value = (double) revolutions; - return new Angle(value*360); - } #else public static Angle FromRevolutions(QuantityValue revolutions) +#endif { double value = (double) revolutions; - return new Angle((value*360)); + return new Angle(value, AngleUnit.Revolution); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -730,40 +649,7 @@ public static Angle From(double value, AngleUnit fromUnit) public static Angle From(QuantityValue value, AngleUnit fromUnit) #endif { - switch (fromUnit) - { - case AngleUnit.Arcminute: - return FromArcminutes(value); - case AngleUnit.Arcsecond: - return FromArcseconds(value); - case AngleUnit.Centiradian: - return FromCentiradians(value); - case AngleUnit.Deciradian: - return FromDeciradians(value); - case AngleUnit.Degree: - return FromDegrees(value); - case AngleUnit.Gradian: - return FromGradians(value); - case AngleUnit.Microdegree: - return FromMicrodegrees(value); - case AngleUnit.Microradian: - return FromMicroradians(value); - case AngleUnit.Millidegree: - return FromMillidegrees(value); - case AngleUnit.Milliradian: - return FromMilliradians(value); - case AngleUnit.Nanodegree: - return FromNanodegrees(value); - case AngleUnit.Nanoradian: - return FromNanoradians(value); - case AngleUnit.Radian: - return FromRadians(value); - case AngleUnit.Revolution: - return FromRevolutions(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Angle((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -780,40 +666,8 @@ public static Angle From(QuantityValue value, AngleUnit fromUnit) { return null; } - switch (fromUnit) - { - case AngleUnit.Arcminute: - return FromArcminutes(value.Value); - case AngleUnit.Arcsecond: - return FromArcseconds(value.Value); - case AngleUnit.Centiradian: - return FromCentiradians(value.Value); - case AngleUnit.Deciradian: - return FromDeciradians(value.Value); - case AngleUnit.Degree: - return FromDegrees(value.Value); - case AngleUnit.Gradian: - return FromGradians(value.Value); - case AngleUnit.Microdegree: - return FromMicrodegrees(value.Value); - case AngleUnit.Microradian: - return FromMicroradians(value.Value); - case AngleUnit.Millidegree: - return FromMillidegrees(value.Value); - case AngleUnit.Milliradian: - return FromMilliradians(value.Value); - case AngleUnit.Nanodegree: - return FromNanodegrees(value.Value); - case AngleUnit.Nanoradian: - return FromNanoradians(value.Value); - case AngleUnit.Radian: - return FromRadians(value.Value); - case AngleUnit.Revolution: - return FromRevolutions(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Angle((double)value.Value, fromUnit); } #endif @@ -832,12 +686,29 @@ public static string GetAbbreviation(AngleUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(AngleUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + AngleUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -848,37 +719,37 @@ public static string GetAbbreviation(AngleUnit unit, [CanBeNull] Culture culture #if !WINDOWS_UWP public static Angle operator -(Angle right) { - return new Angle(-right._degrees); + return new Angle(-right.Value, right.Unit); } public static Angle operator +(Angle left, Angle right) { - return new Angle(left._degrees + right._degrees); + return new Angle(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Angle operator -(Angle left, Angle right) { - return new Angle(left._degrees - right._degrees); + return new Angle(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Angle operator *(double left, Angle right) { - return new Angle(left*right._degrees); + return new Angle(left * right.Value, right.Unit); } public static Angle operator *(Angle left, double right) { - return new Angle(left._degrees*(double)right); + return new Angle(left.Value * right, left.Unit); } public static Angle operator /(Angle left, double right) { - return new Angle(left._degrees/(double)right); + return new Angle(left.Value / right, left.Unit); } public static double operator /(Angle left, Angle right) { - return Convert.ToDouble(left._degrees/right._degrees); + return left.Degrees / right.Degrees; } #endif @@ -901,43 +772,43 @@ public int CompareTo(object obj) #endif int CompareTo(Angle other) { - return _degrees.CompareTo(other._degrees); + return AsBaseUnitDegrees().CompareTo(other.AsBaseUnitDegrees()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Angle left, Angle right) { - return left._degrees <= right._degrees; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Angle left, Angle right) { - return left._degrees >= right._degrees; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Angle left, Angle right) { - return left._degrees < right._degrees; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Angle left, Angle right) { - return left._degrees > right._degrees; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Angle left, Angle right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._degrees == right._degrees; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Angle left, Angle right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._degrees != right._degrees; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -949,7 +820,7 @@ public override bool Equals(object obj) return false; } - return _degrees.Equals(((Angle) obj)._degrees); + return AsBaseUnitDegrees().Equals(((Angle) obj).AsBaseUnitDegrees()); } /// @@ -962,12 +833,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Angle other, Angle maxError) { - return Math.Abs(_degrees - other._degrees) <= maxError._degrees; + return Math.Abs(AsBaseUnitDegrees() - other.AsBaseUnitDegrees()) <= maxError.AsBaseUnitDegrees(); } public override int GetHashCode() { - return _degrees.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -977,40 +848,32 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(AngleUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitDegrees(); + switch (unit) { - case AngleUnit.Arcminute: - return Arcminutes; - case AngleUnit.Arcsecond: - return Arcseconds; - case AngleUnit.Centiradian: - return Centiradians; - case AngleUnit.Deciradian: - return Deciradians; - case AngleUnit.Degree: - return Degrees; - case AngleUnit.Gradian: - return Gradians; - case AngleUnit.Microdegree: - return Microdegrees; - case AngleUnit.Microradian: - return Microradians; - case AngleUnit.Millidegree: - return Millidegrees; - case AngleUnit.Milliradian: - return Milliradians; - case AngleUnit.Nanodegree: - return Nanodegrees; - case AngleUnit.Nanoradian: - return Nanoradians; - case AngleUnit.Radian: - return Radians; - case AngleUnit.Revolution: - return Revolutions; + case AngleUnit.Arcminute: return baseUnitValue*60; + case AngleUnit.Arcsecond: return baseUnitValue*3600; + case AngleUnit.Centiradian: return (baseUnitValue/180*Math.PI) / 1e-2d; + case AngleUnit.Deciradian: return (baseUnitValue/180*Math.PI) / 1e-1d; + case AngleUnit.Degree: return baseUnitValue; + case AngleUnit.Gradian: return baseUnitValue/0.9; + case AngleUnit.Microdegree: return (baseUnitValue) / 1e-6d; + case AngleUnit.Microradian: return (baseUnitValue/180*Math.PI) / 1e-6d; + case AngleUnit.Millidegree: return (baseUnitValue) / 1e-3d; + case AngleUnit.Milliradian: return (baseUnitValue/180*Math.PI) / 1e-3d; + case AngleUnit.Nanodegree: return (baseUnitValue) / 1e-9d; + case AngleUnit.Nanoradian: return (baseUnitValue/180*Math.PI) / 1e-9d; + case AngleUnit.Radian: return baseUnitValue/180*Math.PI; + case AngleUnit.Revolution: return baseUnitValue/360; default: throw new NotImplementedException("unit: " + unit); @@ -1052,7 +915,11 @@ public static Angle Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1071,17 +938,24 @@ public static Angle Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Angle Parse(string str, [CanBeNull] Culture culture) + public static Angle Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1107,16 +981,41 @@ public static bool TryParse([CanBeNull] string str, out Angle result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Angle result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Angle result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1129,6 +1028,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1142,11 +1042,14 @@ public static AngleUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static AngleUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1155,6 +1058,8 @@ public static AngleUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1167,18 +1072,18 @@ public static AngleUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static AngleUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static AngleUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == AngleUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AngleUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1187,6 +1092,7 @@ static AngleUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Degree /// @@ -1198,7 +1104,7 @@ static AngleUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1215,74 +1121,142 @@ public string ToString(AngleUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(AngleUnit unit, [CanBeNull] Culture culture) + public string ToString( + AngleUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(AngleUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + AngleUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(AngleUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + AngleUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Angle /// - public static Angle MaxValue - { - get - { - return new Angle(double.MaxValue); - } - } + public static Angle MaxValue => new Angle(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Angle /// - public static Angle MinValue + public static Angle MinValue => new Angle(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitDegrees() { - get + if (Unit == AngleUnit.Degree) { return _value; } + + switch (Unit) { - return new Angle(double.MinValue); - } - } - } + case AngleUnit.Arcminute: return _value/60; + case AngleUnit.Arcsecond: return _value/3600; + case AngleUnit.Centiradian: return (_value*180/Math.PI) * 1e-2d; + case AngleUnit.Deciradian: return (_value*180/Math.PI) * 1e-1d; + case AngleUnit.Degree: return _value; + case AngleUnit.Gradian: return _value*0.9; + case AngleUnit.Microdegree: return (_value) * 1e-6d; + case AngleUnit.Microradian: return (_value*180/Math.PI) * 1e-6d; + case AngleUnit.Millidegree: return (_value) * 1e-3d; + case AngleUnit.Milliradian: return (_value*180/Math.PI) * 1e-3d; + case AngleUnit.Nanodegree: return (_value) * 1e-9d; + case AngleUnit.Nanoradian: return (_value*180/Math.PI) * 1e-9d; + case AngleUnit.Radian: return _value*180/Math.PI; + case AngleUnit.Revolution: return _value*360; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(AngleUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs index 8af2b188f8..10649f8a1e 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentEnergy.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ApparentEnergy : IComparable, IComparable #endif { /// - /// Base unit of ApparentEnergy. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ApparentEnergyUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _voltampereHours; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ApparentEnergy() : this(0) + public ApparentEnergy() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ApparentEnergy(double voltamperehours) { - _voltampereHours = Convert.ToDouble(voltamperehours); + _value = Convert.ToDouble(voltamperehours); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ApparentEnergy(double numericValue, ApparentEnergyUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit VoltampereHour. + /// + /// Value assuming base unit VoltampereHour. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ApparentEnergy(long voltamperehours) - { - _voltampereHours = Convert.ToDouble(voltamperehours); - } + ApparentEnergy(long voltamperehours) : this(Convert.ToDouble(voltamperehours), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit VoltampereHour. + /// + /// Value assuming base unit VoltampereHour. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ApparentEnergy(decimal voltamperehours) - { - _voltampereHours = Convert.ToDouble(voltamperehours); - } + ApparentEnergy(decimal voltamperehours) : this(Convert.ToDouble(voltamperehours), BaseUnit) { } #region Properties @@ -119,48 +156,30 @@ public ApparentEnergy(double voltamperehours) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ApparentEnergyUnit BaseUnit - { - get { return ApparentEnergyUnit.VoltampereHour; } - } + public static ApparentEnergyUnit BaseUnit => ApparentEnergyUnit.VoltampereHour; /// /// All units of measurement for the ApparentEnergy quantity. /// public static ApparentEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ApparentEnergyUnit)).Cast().ToArray(); - /// /// Get ApparentEnergy in KilovoltampereHours. /// - public double KilovoltampereHours - { - get { return (_voltampereHours) / 1e3d; } - } - + public double KilovoltampereHours => As(ApparentEnergyUnit.KilovoltampereHour); /// /// Get ApparentEnergy in MegavoltampereHours. /// - public double MegavoltampereHours - { - get { return (_voltampereHours) / 1e6d; } - } - + public double MegavoltampereHours => As(ApparentEnergyUnit.MegavoltampereHour); /// /// Get ApparentEnergy in VoltampereHours. /// - public double VoltampereHours - { - get { return _voltampereHours; } - } + public double VoltampereHours => As(ApparentEnergyUnit.VoltampereHour); #endregion #region Static - public static ApparentEnergy Zero - { - get { return new ApparentEnergy(); } - } + public static ApparentEnergy Zero => new ApparentEnergy(0, BaseUnit); /// /// Get ApparentEnergy from KilovoltampereHours. @@ -168,17 +187,13 @@ public static ApparentEnergy Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ApparentEnergy FromKilovoltampereHours(double kilovoltamperehours) - { - double value = (double) kilovoltamperehours; - return new ApparentEnergy((value) * 1e3d); - } #else public static ApparentEnergy FromKilovoltampereHours(QuantityValue kilovoltamperehours) +#endif { double value = (double) kilovoltamperehours; - return new ApparentEnergy(((value) * 1e3d)); + return new ApparentEnergy(value, ApparentEnergyUnit.KilovoltampereHour); } -#endif /// /// Get ApparentEnergy from MegavoltampereHours. @@ -186,17 +201,13 @@ public static ApparentEnergy FromKilovoltampereHours(QuantityValue kilovoltamper #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ApparentEnergy FromMegavoltampereHours(double megavoltamperehours) - { - double value = (double) megavoltamperehours; - return new ApparentEnergy((value) * 1e6d); - } #else public static ApparentEnergy FromMegavoltampereHours(QuantityValue megavoltamperehours) +#endif { double value = (double) megavoltamperehours; - return new ApparentEnergy(((value) * 1e6d)); + return new ApparentEnergy(value, ApparentEnergyUnit.MegavoltampereHour); } -#endif /// /// Get ApparentEnergy from VoltampereHours. @@ -204,17 +215,13 @@ public static ApparentEnergy FromMegavoltampereHours(QuantityValue megavoltamper #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ApparentEnergy FromVoltampereHours(double voltamperehours) - { - double value = (double) voltamperehours; - return new ApparentEnergy(value); - } #else public static ApparentEnergy FromVoltampereHours(QuantityValue voltamperehours) +#endif { double value = (double) voltamperehours; - return new ApparentEnergy((value)); + return new ApparentEnergy(value, ApparentEnergyUnit.VoltampereHour); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -279,18 +286,7 @@ public static ApparentEnergy From(double value, ApparentEnergyUnit fromUnit) public static ApparentEnergy From(QuantityValue value, ApparentEnergyUnit fromUnit) #endif { - switch (fromUnit) - { - case ApparentEnergyUnit.KilovoltampereHour: - return FromKilovoltampereHours(value); - case ApparentEnergyUnit.MegavoltampereHour: - return FromMegavoltampereHours(value); - case ApparentEnergyUnit.VoltampereHour: - return FromVoltampereHours(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ApparentEnergy((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -307,18 +303,8 @@ public static ApparentEnergy From(QuantityValue value, ApparentEnergyUnit fromUn { return null; } - switch (fromUnit) - { - case ApparentEnergyUnit.KilovoltampereHour: - return FromKilovoltampereHours(value.Value); - case ApparentEnergyUnit.MegavoltampereHour: - return FromMegavoltampereHours(value.Value); - case ApparentEnergyUnit.VoltampereHour: - return FromVoltampereHours(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ApparentEnergy((double)value.Value, fromUnit); } #endif @@ -337,12 +323,29 @@ public static string GetAbbreviation(ApparentEnergyUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ApparentEnergyUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ApparentEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -353,37 +356,37 @@ public static string GetAbbreviation(ApparentEnergyUnit unit, [CanBeNull] Cultur #if !WINDOWS_UWP public static ApparentEnergy operator -(ApparentEnergy right) { - return new ApparentEnergy(-right._voltampereHours); + return new ApparentEnergy(-right.Value, right.Unit); } public static ApparentEnergy operator +(ApparentEnergy left, ApparentEnergy right) { - return new ApparentEnergy(left._voltampereHours + right._voltampereHours); + return new ApparentEnergy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ApparentEnergy operator -(ApparentEnergy left, ApparentEnergy right) { - return new ApparentEnergy(left._voltampereHours - right._voltampereHours); + return new ApparentEnergy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ApparentEnergy operator *(double left, ApparentEnergy right) { - return new ApparentEnergy(left*right._voltampereHours); + return new ApparentEnergy(left * right.Value, right.Unit); } public static ApparentEnergy operator *(ApparentEnergy left, double right) { - return new ApparentEnergy(left._voltampereHours*(double)right); + return new ApparentEnergy(left.Value * right, left.Unit); } public static ApparentEnergy operator /(ApparentEnergy left, double right) { - return new ApparentEnergy(left._voltampereHours/(double)right); + return new ApparentEnergy(left.Value / right, left.Unit); } public static double operator /(ApparentEnergy left, ApparentEnergy right) { - return Convert.ToDouble(left._voltampereHours/right._voltampereHours); + return left.VoltampereHours / right.VoltampereHours; } #endif @@ -406,43 +409,43 @@ public int CompareTo(object obj) #endif int CompareTo(ApparentEnergy other) { - return _voltampereHours.CompareTo(other._voltampereHours); + return AsBaseUnitVoltampereHours().CompareTo(other.AsBaseUnitVoltampereHours()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ApparentEnergy left, ApparentEnergy right) { - return left._voltampereHours <= right._voltampereHours; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ApparentEnergy left, ApparentEnergy right) { - return left._voltampereHours >= right._voltampereHours; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ApparentEnergy left, ApparentEnergy right) { - return left._voltampereHours < right._voltampereHours; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ApparentEnergy left, ApparentEnergy right) { - return left._voltampereHours > right._voltampereHours; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ApparentEnergy left, ApparentEnergy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltampereHours == right._voltampereHours; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ApparentEnergy left, ApparentEnergy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltampereHours != right._voltampereHours; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -454,7 +457,7 @@ public override bool Equals(object obj) return false; } - return _voltampereHours.Equals(((ApparentEnergy) obj)._voltampereHours); + return AsBaseUnitVoltampereHours().Equals(((ApparentEnergy) obj).AsBaseUnitVoltampereHours()); } /// @@ -467,12 +470,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ApparentEnergy other, ApparentEnergy maxError) { - return Math.Abs(_voltampereHours - other._voltampereHours) <= maxError._voltampereHours; + return Math.Abs(AsBaseUnitVoltampereHours() - other.AsBaseUnitVoltampereHours()) <= maxError.AsBaseUnitVoltampereHours(); } public override int GetHashCode() { - return _voltampereHours.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -482,18 +485,21 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ApparentEnergyUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitVoltampereHours(); + switch (unit) { - case ApparentEnergyUnit.KilovoltampereHour: - return KilovoltampereHours; - case ApparentEnergyUnit.MegavoltampereHour: - return MegavoltampereHours; - case ApparentEnergyUnit.VoltampereHour: - return VoltampereHours; + case ApparentEnergyUnit.KilovoltampereHour: return (baseUnitValue) / 1e3d; + case ApparentEnergyUnit.MegavoltampereHour: return (baseUnitValue) / 1e6d; + case ApparentEnergyUnit.VoltampereHour: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -535,7 +541,11 @@ public static ApparentEnergy Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -554,17 +564,24 @@ public static ApparentEnergy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ApparentEnergy Parse(string str, [CanBeNull] Culture culture) + public static ApparentEnergy Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -590,16 +607,41 @@ public static bool TryParse([CanBeNull] string str, out ApparentEnergy result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ApparentEnergy result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ApparentEnergy result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -612,6 +654,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -625,11 +668,14 @@ public static ApparentEnergyUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ApparentEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -638,6 +684,8 @@ public static ApparentEnergyUnit ParseUnit(string str, [CanBeNull] string cultur /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -650,18 +698,18 @@ public static ApparentEnergyUnit ParseUnit(string str, [CanBeNull] string cultur #else public #endif - static ApparentEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ApparentEnergyUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ApparentEnergyUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ApparentEnergyUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -670,6 +718,7 @@ static ApparentEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is VoltampereHour /// @@ -681,7 +730,7 @@ static ApparentEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -698,74 +747,131 @@ public string ToString(ApparentEnergyUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ApparentEnergyUnit unit, [CanBeNull] Culture culture) + public string ToString( + ApparentEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ApparentEnergyUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ApparentEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ApparentEnergyUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ApparentEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ApparentEnergy /// - public static ApparentEnergy MaxValue - { - get - { - return new ApparentEnergy(double.MaxValue); - } - } + public static ApparentEnergy MaxValue => new ApparentEnergy(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ApparentEnergy /// - public static ApparentEnergy MinValue + public static ApparentEnergy MinValue => new ApparentEnergy(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitVoltampereHours() { - get + if (Unit == ApparentEnergyUnit.VoltampereHour) { return _value; } + + switch (Unit) { - return new ApparentEnergy(double.MinValue); - } - } - } + case ApparentEnergyUnit.KilovoltampereHour: return (_value) * 1e3d; + case ApparentEnergyUnit.MegavoltampereHour: return (_value) * 1e6d; + case ApparentEnergyUnit.VoltampereHour: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ApparentEnergyUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs b/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs index cd2f9daa44..acc4aa73f2 100644 --- a/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ApparentPower.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ApparentPower : IComparable, IComparable #endif { /// - /// Base unit of ApparentPower. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _voltamperes; + private readonly ApparentPowerUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ApparentPower() : this(0) + public ApparentPower() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ApparentPower(double voltamperes) { - _voltamperes = Convert.ToDouble(voltamperes); + _value = Convert.ToDouble(voltamperes); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ApparentPower(double numericValue, ApparentPowerUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Voltampere. + /// + /// Value assuming base unit Voltampere. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ApparentPower(long voltamperes) - { - _voltamperes = Convert.ToDouble(voltamperes); - } + ApparentPower(long voltamperes) : this(Convert.ToDouble(voltamperes), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Voltampere. + /// + /// Value assuming base unit Voltampere. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ApparentPower(decimal voltamperes) - { - _voltamperes = Convert.ToDouble(voltamperes); - } + ApparentPower(decimal voltamperes) : this(Convert.ToDouble(voltamperes), BaseUnit) { } #region Properties @@ -119,56 +156,34 @@ public ApparentPower(double voltamperes) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ApparentPowerUnit BaseUnit - { - get { return ApparentPowerUnit.Voltampere; } - } + public static ApparentPowerUnit BaseUnit => ApparentPowerUnit.Voltampere; /// /// All units of measurement for the ApparentPower quantity. /// public static ApparentPowerUnit[] Units { get; } = Enum.GetValues(typeof(ApparentPowerUnit)).Cast().ToArray(); - /// /// Get ApparentPower in Gigavoltamperes. /// - public double Gigavoltamperes - { - get { return (_voltamperes) / 1e9d; } - } - + public double Gigavoltamperes => As(ApparentPowerUnit.Gigavoltampere); /// /// Get ApparentPower in Kilovoltamperes. /// - public double Kilovoltamperes - { - get { return (_voltamperes) / 1e3d; } - } - + public double Kilovoltamperes => As(ApparentPowerUnit.Kilovoltampere); /// /// Get ApparentPower in Megavoltamperes. /// - public double Megavoltamperes - { - get { return (_voltamperes) / 1e6d; } - } - + public double Megavoltamperes => As(ApparentPowerUnit.Megavoltampere); /// /// Get ApparentPower in Voltamperes. /// - public double Voltamperes - { - get { return _voltamperes; } - } + public double Voltamperes => As(ApparentPowerUnit.Voltampere); #endregion #region Static - public static ApparentPower Zero - { - get { return new ApparentPower(); } - } + public static ApparentPower Zero => new ApparentPower(0, BaseUnit); /// /// Get ApparentPower from Gigavoltamperes. @@ -176,17 +191,13 @@ public static ApparentPower Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ApparentPower FromGigavoltamperes(double gigavoltamperes) - { - double value = (double) gigavoltamperes; - return new ApparentPower((value) * 1e9d); - } #else public static ApparentPower FromGigavoltamperes(QuantityValue gigavoltamperes) +#endif { double value = (double) gigavoltamperes; - return new ApparentPower(((value) * 1e9d)); + return new ApparentPower(value, ApparentPowerUnit.Gigavoltampere); } -#endif /// /// Get ApparentPower from Kilovoltamperes. @@ -194,17 +205,13 @@ public static ApparentPower FromGigavoltamperes(QuantityValue gigavoltamperes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ApparentPower FromKilovoltamperes(double kilovoltamperes) - { - double value = (double) kilovoltamperes; - return new ApparentPower((value) * 1e3d); - } #else public static ApparentPower FromKilovoltamperes(QuantityValue kilovoltamperes) +#endif { double value = (double) kilovoltamperes; - return new ApparentPower(((value) * 1e3d)); + return new ApparentPower(value, ApparentPowerUnit.Kilovoltampere); } -#endif /// /// Get ApparentPower from Megavoltamperes. @@ -212,17 +219,13 @@ public static ApparentPower FromKilovoltamperes(QuantityValue kilovoltamperes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ApparentPower FromMegavoltamperes(double megavoltamperes) - { - double value = (double) megavoltamperes; - return new ApparentPower((value) * 1e6d); - } #else public static ApparentPower FromMegavoltamperes(QuantityValue megavoltamperes) +#endif { double value = (double) megavoltamperes; - return new ApparentPower(((value) * 1e6d)); + return new ApparentPower(value, ApparentPowerUnit.Megavoltampere); } -#endif /// /// Get ApparentPower from Voltamperes. @@ -230,17 +233,13 @@ public static ApparentPower FromMegavoltamperes(QuantityValue megavoltamperes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ApparentPower FromVoltamperes(double voltamperes) - { - double value = (double) voltamperes; - return new ApparentPower(value); - } #else public static ApparentPower FromVoltamperes(QuantityValue voltamperes) +#endif { double value = (double) voltamperes; - return new ApparentPower((value)); + return new ApparentPower(value, ApparentPowerUnit.Voltampere); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -320,20 +319,7 @@ public static ApparentPower From(double value, ApparentPowerUnit fromUnit) public static ApparentPower From(QuantityValue value, ApparentPowerUnit fromUnit) #endif { - switch (fromUnit) - { - case ApparentPowerUnit.Gigavoltampere: - return FromGigavoltamperes(value); - case ApparentPowerUnit.Kilovoltampere: - return FromKilovoltamperes(value); - case ApparentPowerUnit.Megavoltampere: - return FromMegavoltamperes(value); - case ApparentPowerUnit.Voltampere: - return FromVoltamperes(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ApparentPower((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -350,20 +336,8 @@ public static ApparentPower From(QuantityValue value, ApparentPowerUnit fromUnit { return null; } - switch (fromUnit) - { - case ApparentPowerUnit.Gigavoltampere: - return FromGigavoltamperes(value.Value); - case ApparentPowerUnit.Kilovoltampere: - return FromKilovoltamperes(value.Value); - case ApparentPowerUnit.Megavoltampere: - return FromMegavoltamperes(value.Value); - case ApparentPowerUnit.Voltampere: - return FromVoltamperes(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ApparentPower((double)value.Value, fromUnit); } #endif @@ -382,12 +356,29 @@ public static string GetAbbreviation(ApparentPowerUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ApparentPowerUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ApparentPowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -398,37 +389,37 @@ public static string GetAbbreviation(ApparentPowerUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static ApparentPower operator -(ApparentPower right) { - return new ApparentPower(-right._voltamperes); + return new ApparentPower(-right.Value, right.Unit); } public static ApparentPower operator +(ApparentPower left, ApparentPower right) { - return new ApparentPower(left._voltamperes + right._voltamperes); + return new ApparentPower(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ApparentPower operator -(ApparentPower left, ApparentPower right) { - return new ApparentPower(left._voltamperes - right._voltamperes); + return new ApparentPower(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ApparentPower operator *(double left, ApparentPower right) { - return new ApparentPower(left*right._voltamperes); + return new ApparentPower(left * right.Value, right.Unit); } public static ApparentPower operator *(ApparentPower left, double right) { - return new ApparentPower(left._voltamperes*(double)right); + return new ApparentPower(left.Value * right, left.Unit); } public static ApparentPower operator /(ApparentPower left, double right) { - return new ApparentPower(left._voltamperes/(double)right); + return new ApparentPower(left.Value / right, left.Unit); } public static double operator /(ApparentPower left, ApparentPower right) { - return Convert.ToDouble(left._voltamperes/right._voltamperes); + return left.Voltamperes / right.Voltamperes; } #endif @@ -451,43 +442,43 @@ public int CompareTo(object obj) #endif int CompareTo(ApparentPower other) { - return _voltamperes.CompareTo(other._voltamperes); + return AsBaseUnitVoltamperes().CompareTo(other.AsBaseUnitVoltamperes()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ApparentPower left, ApparentPower right) { - return left._voltamperes <= right._voltamperes; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ApparentPower left, ApparentPower right) { - return left._voltamperes >= right._voltamperes; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ApparentPower left, ApparentPower right) { - return left._voltamperes < right._voltamperes; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ApparentPower left, ApparentPower right) { - return left._voltamperes > right._voltamperes; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ApparentPower left, ApparentPower right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltamperes == right._voltamperes; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ApparentPower left, ApparentPower right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltamperes != right._voltamperes; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -499,7 +490,7 @@ public override bool Equals(object obj) return false; } - return _voltamperes.Equals(((ApparentPower) obj)._voltamperes); + return AsBaseUnitVoltamperes().Equals(((ApparentPower) obj).AsBaseUnitVoltamperes()); } /// @@ -512,12 +503,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ApparentPower other, ApparentPower maxError) { - return Math.Abs(_voltamperes - other._voltamperes) <= maxError._voltamperes; + return Math.Abs(AsBaseUnitVoltamperes() - other.AsBaseUnitVoltamperes()) <= maxError.AsBaseUnitVoltamperes(); } public override int GetHashCode() { - return _voltamperes.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -527,20 +518,22 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ApparentPowerUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitVoltamperes(); + switch (unit) { - case ApparentPowerUnit.Gigavoltampere: - return Gigavoltamperes; - case ApparentPowerUnit.Kilovoltampere: - return Kilovoltamperes; - case ApparentPowerUnit.Megavoltampere: - return Megavoltamperes; - case ApparentPowerUnit.Voltampere: - return Voltamperes; + case ApparentPowerUnit.Gigavoltampere: return (baseUnitValue) / 1e9d; + case ApparentPowerUnit.Kilovoltampere: return (baseUnitValue) / 1e3d; + case ApparentPowerUnit.Megavoltampere: return (baseUnitValue) / 1e6d; + case ApparentPowerUnit.Voltampere: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -582,7 +575,11 @@ public static ApparentPower Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -601,17 +598,24 @@ public static ApparentPower Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ApparentPower Parse(string str, [CanBeNull] Culture culture) + public static ApparentPower Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -637,16 +641,41 @@ public static bool TryParse([CanBeNull] string str, out ApparentPower result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ApparentPower result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ApparentPower result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -659,6 +688,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -672,11 +702,14 @@ public static ApparentPowerUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ApparentPowerUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -685,6 +718,8 @@ public static ApparentPowerUnit ParseUnit(string str, [CanBeNull] string culture /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -697,18 +732,18 @@ public static ApparentPowerUnit ParseUnit(string str, [CanBeNull] string culture #else public #endif - static ApparentPowerUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ApparentPowerUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ApparentPowerUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ApparentPowerUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -717,6 +752,7 @@ static ApparentPowerUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Voltampere /// @@ -728,7 +764,7 @@ static ApparentPowerUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -745,74 +781,132 @@ public string ToString(ApparentPowerUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ApparentPowerUnit unit, [CanBeNull] Culture culture) + public string ToString( + ApparentPowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ApparentPowerUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ApparentPowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ApparentPowerUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ApparentPowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ApparentPower /// - public static ApparentPower MaxValue - { - get - { - return new ApparentPower(double.MaxValue); - } - } + public static ApparentPower MaxValue => new ApparentPower(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ApparentPower /// - public static ApparentPower MinValue + public static ApparentPower MinValue => new ApparentPower(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitVoltamperes() { - get + if (Unit == ApparentPowerUnit.Voltampere) { return _value; } + + switch (Unit) { - return new ApparentPower(double.MinValue); - } - } - } + case ApparentPowerUnit.Gigavoltampere: return (_value) * 1e9d; + case ApparentPowerUnit.Kilovoltampere: return (_value) * 1e3d; + case ApparentPowerUnit.Megavoltampere: return (_value) * 1e6d; + case ApparentPowerUnit.Voltampere: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ApparentPowerUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Area.g.cs b/UnitsNet/GeneratedCode/Quantities/Area.g.cs index 44a15ca726..5503e3b57f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Area.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Area.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Area : IComparable, IComparable #endif { /// - /// Base unit of Area. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _squareMeters; + public AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Area() : this(0) + public Area() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Area(double squaremeters) { - _squareMeters = Convert.ToDouble(squaremeters); + _value = Convert.ToDouble(squaremeters); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Area(double numericValue, AreaUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit SquareMeter. + /// + /// Value assuming base unit SquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Area(long squaremeters) - { - _squareMeters = Convert.ToDouble(squaremeters); - } + Area(long squaremeters) : this(Convert.ToDouble(squaremeters), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit SquareMeter. + /// + /// Value assuming base unit SquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Area(decimal squaremeters) - { - _squareMeters = Convert.ToDouble(squaremeters); - } + Area(decimal squaremeters) : this(Convert.ToDouble(squaremeters), BaseUnit) { } #region Properties @@ -119,128 +156,70 @@ public Area(double squaremeters) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static AreaUnit BaseUnit - { - get { return AreaUnit.SquareMeter; } - } + public static AreaUnit BaseUnit => AreaUnit.SquareMeter; /// /// All units of measurement for the Area quantity. /// public static AreaUnit[] Units { get; } = Enum.GetValues(typeof(AreaUnit)).Cast().ToArray(); - /// /// Get Area in Acres. /// - public double Acres - { - get { return _squareMeters/4046.85642; } - } - + public double Acres => As(AreaUnit.Acre); /// /// Get Area in Hectares. /// - public double Hectares - { - get { return _squareMeters/1e4; } - } - + public double Hectares => As(AreaUnit.Hectare); /// /// Get Area in SquareCentimeters. /// - public double SquareCentimeters - { - get { return _squareMeters/1e-4; } - } - + public double SquareCentimeters => As(AreaUnit.SquareCentimeter); /// /// Get Area in SquareDecimeters. /// - public double SquareDecimeters - { - get { return _squareMeters/1e-2; } - } - + public double SquareDecimeters => As(AreaUnit.SquareDecimeter); /// /// Get Area in SquareFeet. /// - public double SquareFeet - { - get { return _squareMeters/0.092903; } - } - + public double SquareFeet => As(AreaUnit.SquareFoot); /// /// Get Area in SquareInches. /// - public double SquareInches - { - get { return _squareMeters/0.00064516; } - } - + public double SquareInches => As(AreaUnit.SquareInch); /// /// Get Area in SquareKilometers. /// - public double SquareKilometers - { - get { return _squareMeters/1e6; } - } - + public double SquareKilometers => As(AreaUnit.SquareKilometer); /// /// Get Area in SquareMeters. /// - public double SquareMeters - { - get { return _squareMeters; } - } - + public double SquareMeters => As(AreaUnit.SquareMeter); /// /// Get Area in SquareMicrometers. /// - public double SquareMicrometers - { - get { return _squareMeters/1e-12; } - } - + public double SquareMicrometers => As(AreaUnit.SquareMicrometer); /// /// Get Area in SquareMiles. /// - public double SquareMiles - { - get { return _squareMeters/2.59e6; } - } - + public double SquareMiles => As(AreaUnit.SquareMile); /// /// Get Area in SquareMillimeters. /// - public double SquareMillimeters - { - get { return _squareMeters/1e-6; } - } - + public double SquareMillimeters => As(AreaUnit.SquareMillimeter); /// /// Get Area in SquareYards. /// - public double SquareYards - { - get { return _squareMeters/0.836127; } - } - + public double SquareYards => As(AreaUnit.SquareYard); /// /// Get Area in UsSurveySquareFeet. /// - public double UsSurveySquareFeet - { - get { return _squareMeters/0.09290341161; } - } + public double UsSurveySquareFeet => As(AreaUnit.UsSurveySquareFoot); #endregion #region Static - public static Area Zero - { - get { return new Area(); } - } + public static Area Zero => new Area(0, BaseUnit); /// /// Get Area from Acres. @@ -248,17 +227,13 @@ public static Area Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromAcres(double acres) - { - double value = (double) acres; - return new Area(value*4046.85642); - } #else public static Area FromAcres(QuantityValue acres) +#endif { double value = (double) acres; - return new Area((value*4046.85642)); + return new Area(value, AreaUnit.Acre); } -#endif /// /// Get Area from Hectares. @@ -266,17 +241,13 @@ public static Area FromAcres(QuantityValue acres) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromHectares(double hectares) - { - double value = (double) hectares; - return new Area(value*1e4); - } #else public static Area FromHectares(QuantityValue hectares) +#endif { double value = (double) hectares; - return new Area((value*1e4)); + return new Area(value, AreaUnit.Hectare); } -#endif /// /// Get Area from SquareCentimeters. @@ -284,17 +255,13 @@ public static Area FromHectares(QuantityValue hectares) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromSquareCentimeters(double squarecentimeters) - { - double value = (double) squarecentimeters; - return new Area(value*1e-4); - } #else public static Area FromSquareCentimeters(QuantityValue squarecentimeters) +#endif { double value = (double) squarecentimeters; - return new Area((value*1e-4)); + return new Area(value, AreaUnit.SquareCentimeter); } -#endif /// /// Get Area from SquareDecimeters. @@ -302,17 +269,13 @@ public static Area FromSquareCentimeters(QuantityValue squarecentimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromSquareDecimeters(double squaredecimeters) - { - double value = (double) squaredecimeters; - return new Area(value*1e-2); - } #else public static Area FromSquareDecimeters(QuantityValue squaredecimeters) +#endif { double value = (double) squaredecimeters; - return new Area((value*1e-2)); + return new Area(value, AreaUnit.SquareDecimeter); } -#endif /// /// Get Area from SquareFeet. @@ -320,17 +283,13 @@ public static Area FromSquareDecimeters(QuantityValue squaredecimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromSquareFeet(double squarefeet) - { - double value = (double) squarefeet; - return new Area(value*0.092903); - } #else public static Area FromSquareFeet(QuantityValue squarefeet) +#endif { double value = (double) squarefeet; - return new Area((value*0.092903)); + return new Area(value, AreaUnit.SquareFoot); } -#endif /// /// Get Area from SquareInches. @@ -338,17 +297,13 @@ public static Area FromSquareFeet(QuantityValue squarefeet) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromSquareInches(double squareinches) - { - double value = (double) squareinches; - return new Area(value*0.00064516); - } #else public static Area FromSquareInches(QuantityValue squareinches) +#endif { double value = (double) squareinches; - return new Area((value*0.00064516)); + return new Area(value, AreaUnit.SquareInch); } -#endif /// /// Get Area from SquareKilometers. @@ -356,17 +311,13 @@ public static Area FromSquareInches(QuantityValue squareinches) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromSquareKilometers(double squarekilometers) - { - double value = (double) squarekilometers; - return new Area(value*1e6); - } #else public static Area FromSquareKilometers(QuantityValue squarekilometers) +#endif { double value = (double) squarekilometers; - return new Area((value*1e6)); + return new Area(value, AreaUnit.SquareKilometer); } -#endif /// /// Get Area from SquareMeters. @@ -374,17 +325,13 @@ public static Area FromSquareKilometers(QuantityValue squarekilometers) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromSquareMeters(double squaremeters) - { - double value = (double) squaremeters; - return new Area(value); - } #else public static Area FromSquareMeters(QuantityValue squaremeters) +#endif { double value = (double) squaremeters; - return new Area((value)); + return new Area(value, AreaUnit.SquareMeter); } -#endif /// /// Get Area from SquareMicrometers. @@ -392,17 +339,13 @@ public static Area FromSquareMeters(QuantityValue squaremeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromSquareMicrometers(double squaremicrometers) - { - double value = (double) squaremicrometers; - return new Area(value*1e-12); - } #else public static Area FromSquareMicrometers(QuantityValue squaremicrometers) +#endif { double value = (double) squaremicrometers; - return new Area((value*1e-12)); + return new Area(value, AreaUnit.SquareMicrometer); } -#endif /// /// Get Area from SquareMiles. @@ -410,17 +353,13 @@ public static Area FromSquareMicrometers(QuantityValue squaremicrometers) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromSquareMiles(double squaremiles) - { - double value = (double) squaremiles; - return new Area(value*2.59e6); - } #else public static Area FromSquareMiles(QuantityValue squaremiles) +#endif { double value = (double) squaremiles; - return new Area((value*2.59e6)); + return new Area(value, AreaUnit.SquareMile); } -#endif /// /// Get Area from SquareMillimeters. @@ -428,17 +367,13 @@ public static Area FromSquareMiles(QuantityValue squaremiles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromSquareMillimeters(double squaremillimeters) - { - double value = (double) squaremillimeters; - return new Area(value*1e-6); - } #else public static Area FromSquareMillimeters(QuantityValue squaremillimeters) +#endif { double value = (double) squaremillimeters; - return new Area((value*1e-6)); + return new Area(value, AreaUnit.SquareMillimeter); } -#endif /// /// Get Area from SquareYards. @@ -446,17 +381,13 @@ public static Area FromSquareMillimeters(QuantityValue squaremillimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromSquareYards(double squareyards) - { - double value = (double) squareyards; - return new Area(value*0.836127); - } #else public static Area FromSquareYards(QuantityValue squareyards) +#endif { double value = (double) squareyards; - return new Area((value*0.836127)); + return new Area(value, AreaUnit.SquareYard); } -#endif /// /// Get Area from UsSurveySquareFeet. @@ -464,17 +395,13 @@ public static Area FromSquareYards(QuantityValue squareyards) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Area FromUsSurveySquareFeet(double ussurveysquarefeet) - { - double value = (double) ussurveysquarefeet; - return new Area(value*0.09290341161); - } #else public static Area FromUsSurveySquareFeet(QuantityValue ussurveysquarefeet) +#endif { double value = (double) ussurveysquarefeet; - return new Area((value*0.09290341161)); + return new Area(value, AreaUnit.UsSurveySquareFoot); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -689,38 +616,7 @@ public static Area From(double value, AreaUnit fromUnit) public static Area From(QuantityValue value, AreaUnit fromUnit) #endif { - switch (fromUnit) - { - case AreaUnit.Acre: - return FromAcres(value); - case AreaUnit.Hectare: - return FromHectares(value); - case AreaUnit.SquareCentimeter: - return FromSquareCentimeters(value); - case AreaUnit.SquareDecimeter: - return FromSquareDecimeters(value); - case AreaUnit.SquareFoot: - return FromSquareFeet(value); - case AreaUnit.SquareInch: - return FromSquareInches(value); - case AreaUnit.SquareKilometer: - return FromSquareKilometers(value); - case AreaUnit.SquareMeter: - return FromSquareMeters(value); - case AreaUnit.SquareMicrometer: - return FromSquareMicrometers(value); - case AreaUnit.SquareMile: - return FromSquareMiles(value); - case AreaUnit.SquareMillimeter: - return FromSquareMillimeters(value); - case AreaUnit.SquareYard: - return FromSquareYards(value); - case AreaUnit.UsSurveySquareFoot: - return FromUsSurveySquareFeet(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Area((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -737,38 +633,8 @@ public static Area From(QuantityValue value, AreaUnit fromUnit) { return null; } - switch (fromUnit) - { - case AreaUnit.Acre: - return FromAcres(value.Value); - case AreaUnit.Hectare: - return FromHectares(value.Value); - case AreaUnit.SquareCentimeter: - return FromSquareCentimeters(value.Value); - case AreaUnit.SquareDecimeter: - return FromSquareDecimeters(value.Value); - case AreaUnit.SquareFoot: - return FromSquareFeet(value.Value); - case AreaUnit.SquareInch: - return FromSquareInches(value.Value); - case AreaUnit.SquareKilometer: - return FromSquareKilometers(value.Value); - case AreaUnit.SquareMeter: - return FromSquareMeters(value.Value); - case AreaUnit.SquareMicrometer: - return FromSquareMicrometers(value.Value); - case AreaUnit.SquareMile: - return FromSquareMiles(value.Value); - case AreaUnit.SquareMillimeter: - return FromSquareMillimeters(value.Value); - case AreaUnit.SquareYard: - return FromSquareYards(value.Value); - case AreaUnit.UsSurveySquareFoot: - return FromUsSurveySquareFeet(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Area((double)value.Value, fromUnit); } #endif @@ -787,12 +653,29 @@ public static string GetAbbreviation(AreaUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(AreaUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + AreaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -803,37 +686,37 @@ public static string GetAbbreviation(AreaUnit unit, [CanBeNull] Culture culture) #if !WINDOWS_UWP public static Area operator -(Area right) { - return new Area(-right._squareMeters); + return new Area(-right.Value, right.Unit); } public static Area operator +(Area left, Area right) { - return new Area(left._squareMeters + right._squareMeters); + return new Area(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Area operator -(Area left, Area right) { - return new Area(left._squareMeters - right._squareMeters); + return new Area(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Area operator *(double left, Area right) { - return new Area(left*right._squareMeters); + return new Area(left * right.Value, right.Unit); } public static Area operator *(Area left, double right) { - return new Area(left._squareMeters*(double)right); + return new Area(left.Value * right, left.Unit); } public static Area operator /(Area left, double right) { - return new Area(left._squareMeters/(double)right); + return new Area(left.Value / right, left.Unit); } public static double operator /(Area left, Area right) { - return Convert.ToDouble(left._squareMeters/right._squareMeters); + return left.SquareMeters / right.SquareMeters; } #endif @@ -856,43 +739,43 @@ public int CompareTo(object obj) #endif int CompareTo(Area other) { - return _squareMeters.CompareTo(other._squareMeters); + return AsBaseUnitSquareMeters().CompareTo(other.AsBaseUnitSquareMeters()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Area left, Area right) { - return left._squareMeters <= right._squareMeters; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Area left, Area right) { - return left._squareMeters >= right._squareMeters; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Area left, Area right) { - return left._squareMeters < right._squareMeters; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Area left, Area right) { - return left._squareMeters > right._squareMeters; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Area left, Area right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._squareMeters == right._squareMeters; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Area left, Area right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._squareMeters != right._squareMeters; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -904,7 +787,7 @@ public override bool Equals(object obj) return false; } - return _squareMeters.Equals(((Area) obj)._squareMeters); + return AsBaseUnitSquareMeters().Equals(((Area) obj).AsBaseUnitSquareMeters()); } /// @@ -917,12 +800,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Area other, Area maxError) { - return Math.Abs(_squareMeters - other._squareMeters) <= maxError._squareMeters; + return Math.Abs(AsBaseUnitSquareMeters() - other.AsBaseUnitSquareMeters()) <= maxError.AsBaseUnitSquareMeters(); } public override int GetHashCode() { - return _squareMeters.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -932,38 +815,31 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(AreaUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitSquareMeters(); + switch (unit) { - case AreaUnit.Acre: - return Acres; - case AreaUnit.Hectare: - return Hectares; - case AreaUnit.SquareCentimeter: - return SquareCentimeters; - case AreaUnit.SquareDecimeter: - return SquareDecimeters; - case AreaUnit.SquareFoot: - return SquareFeet; - case AreaUnit.SquareInch: - return SquareInches; - case AreaUnit.SquareKilometer: - return SquareKilometers; - case AreaUnit.SquareMeter: - return SquareMeters; - case AreaUnit.SquareMicrometer: - return SquareMicrometers; - case AreaUnit.SquareMile: - return SquareMiles; - case AreaUnit.SquareMillimeter: - return SquareMillimeters; - case AreaUnit.SquareYard: - return SquareYards; - case AreaUnit.UsSurveySquareFoot: - return UsSurveySquareFeet; + case AreaUnit.Acre: return baseUnitValue/4046.85642; + case AreaUnit.Hectare: return baseUnitValue/1e4; + case AreaUnit.SquareCentimeter: return baseUnitValue/1e-4; + case AreaUnit.SquareDecimeter: return baseUnitValue/1e-2; + case AreaUnit.SquareFoot: return baseUnitValue/0.092903; + case AreaUnit.SquareInch: return baseUnitValue/0.00064516; + case AreaUnit.SquareKilometer: return baseUnitValue/1e6; + case AreaUnit.SquareMeter: return baseUnitValue; + case AreaUnit.SquareMicrometer: return baseUnitValue/1e-12; + case AreaUnit.SquareMile: return baseUnitValue/2.59e6; + case AreaUnit.SquareMillimeter: return baseUnitValue/1e-6; + case AreaUnit.SquareYard: return baseUnitValue/0.836127; + case AreaUnit.UsSurveySquareFoot: return baseUnitValue/0.09290341161; default: throw new NotImplementedException("unit: " + unit); @@ -1005,7 +881,11 @@ public static Area Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1024,17 +904,24 @@ public static Area Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Area Parse(string str, [CanBeNull] Culture culture) + public static Area Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1060,16 +947,41 @@ public static bool TryParse([CanBeNull] string str, out Area result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Area result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Area result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1082,6 +994,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1095,11 +1008,14 @@ public static AreaUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static AreaUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1108,6 +1024,8 @@ public static AreaUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1120,18 +1038,18 @@ public static AreaUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static AreaUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static AreaUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == AreaUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1140,6 +1058,7 @@ static AreaUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is SquareMeter /// @@ -1151,7 +1070,7 @@ static AreaUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1168,74 +1087,141 @@ public string ToString(AreaUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(AreaUnit unit, [CanBeNull] Culture culture) + public string ToString( + AreaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(AreaUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + AreaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(AreaUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + AreaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Area /// - public static Area MaxValue - { - get - { - return new Area(double.MaxValue); - } - } + public static Area MaxValue => new Area(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Area /// - public static Area MinValue + public static Area MinValue => new Area(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitSquareMeters() { - get + if (Unit == AreaUnit.SquareMeter) { return _value; } + + switch (Unit) { - return new Area(double.MinValue); - } - } - } + case AreaUnit.Acre: return _value*4046.85642; + case AreaUnit.Hectare: return _value*1e4; + case AreaUnit.SquareCentimeter: return _value*1e-4; + case AreaUnit.SquareDecimeter: return _value*1e-2; + case AreaUnit.SquareFoot: return _value*0.092903; + case AreaUnit.SquareInch: return _value*0.00064516; + case AreaUnit.SquareKilometer: return _value*1e6; + case AreaUnit.SquareMeter: return _value; + case AreaUnit.SquareMicrometer: return _value*1e-12; + case AreaUnit.SquareMile: return _value*2.59e6; + case AreaUnit.SquareMillimeter: return _value*1e-6; + case AreaUnit.SquareYard: return _value*0.836127; + case AreaUnit.UsSurveySquareFoot: return _value*0.09290341161; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(AreaUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs index 430db5720c..d653e80c23 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct AreaDensity : IComparable, IComparable #endif { /// - /// Base unit of AreaDensity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaDensityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _kilogramsPerSquareMeter; + public AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public AreaDensity() : this(0) + public AreaDensity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public AreaDensity(double kilogramspersquaremeter) { - _kilogramsPerSquareMeter = Convert.ToDouble(kilogramspersquaremeter); + _value = Convert.ToDouble(kilogramspersquaremeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + AreaDensity(double numericValue, AreaDensityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerSquareMeter. + /// + /// Value assuming base unit KilogramPerSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - AreaDensity(long kilogramspersquaremeter) - { - _kilogramsPerSquareMeter = Convert.ToDouble(kilogramspersquaremeter); - } + AreaDensity(long kilogramspersquaremeter) : this(Convert.ToDouble(kilogramspersquaremeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerSquareMeter. + /// + /// Value assuming base unit KilogramPerSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - AreaDensity(decimal kilogramspersquaremeter) - { - _kilogramsPerSquareMeter = Convert.ToDouble(kilogramspersquaremeter); - } + AreaDensity(decimal kilogramspersquaremeter) : this(Convert.ToDouble(kilogramspersquaremeter), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public AreaDensity(double kilogramspersquaremeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static AreaDensityUnit BaseUnit - { - get { return AreaDensityUnit.KilogramPerSquareMeter; } - } + public static AreaDensityUnit BaseUnit => AreaDensityUnit.KilogramPerSquareMeter; /// /// All units of measurement for the AreaDensity quantity. /// public static AreaDensityUnit[] Units { get; } = Enum.GetValues(typeof(AreaDensityUnit)).Cast().ToArray(); - /// /// Get AreaDensity in KilogramsPerSquareMeter. /// - public double KilogramsPerSquareMeter - { - get { return _kilogramsPerSquareMeter; } - } + public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); #endregion #region Static - public static AreaDensity Zero - { - get { return new AreaDensity(); } - } + public static AreaDensity Zero => new AreaDensity(0, BaseUnit); /// /// Get AreaDensity from KilogramsPerSquareMeter. @@ -152,17 +179,13 @@ public static AreaDensity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AreaDensity FromKilogramsPerSquareMeter(double kilogramspersquaremeter) - { - double value = (double) kilogramspersquaremeter; - return new AreaDensity(value); - } #else public static AreaDensity FromKilogramsPerSquareMeter(QuantityValue kilogramspersquaremeter) +#endif { double value = (double) kilogramspersquaremeter; - return new AreaDensity((value)); + return new AreaDensity(value, AreaDensityUnit.KilogramPerSquareMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static AreaDensity From(double value, AreaDensityUnit fromUnit) public static AreaDensity From(QuantityValue value, AreaDensityUnit fromUnit) #endif { - switch (fromUnit) - { - case AreaDensityUnit.KilogramPerSquareMeter: - return FromKilogramsPerSquareMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new AreaDensity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static AreaDensity From(QuantityValue value, AreaDensityUnit fromUnit) { return null; } - switch (fromUnit) - { - case AreaDensityUnit.KilogramPerSquareMeter: - return FromKilogramsPerSquareMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new AreaDensity((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(AreaDensityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(AreaDensityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + AreaDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(AreaDensityUnit unit, [CanBeNull] Culture c #if !WINDOWS_UWP public static AreaDensity operator -(AreaDensity right) { - return new AreaDensity(-right._kilogramsPerSquareMeter); + return new AreaDensity(-right.Value, right.Unit); } public static AreaDensity operator +(AreaDensity left, AreaDensity right) { - return new AreaDensity(left._kilogramsPerSquareMeter + right._kilogramsPerSquareMeter); + return new AreaDensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static AreaDensity operator -(AreaDensity left, AreaDensity right) { - return new AreaDensity(left._kilogramsPerSquareMeter - right._kilogramsPerSquareMeter); + return new AreaDensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static AreaDensity operator *(double left, AreaDensity right) { - return new AreaDensity(left*right._kilogramsPerSquareMeter); + return new AreaDensity(left * right.Value, right.Unit); } public static AreaDensity operator *(AreaDensity left, double right) { - return new AreaDensity(left._kilogramsPerSquareMeter*(double)right); + return new AreaDensity(left.Value * right, left.Unit); } public static AreaDensity operator /(AreaDensity left, double right) { - return new AreaDensity(left._kilogramsPerSquareMeter/(double)right); + return new AreaDensity(left.Value / right, left.Unit); } public static double operator /(AreaDensity left, AreaDensity right) { - return Convert.ToDouble(left._kilogramsPerSquareMeter/right._kilogramsPerSquareMeter); + return left.KilogramsPerSquareMeter / right.KilogramsPerSquareMeter; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(AreaDensity other) { - return _kilogramsPerSquareMeter.CompareTo(other._kilogramsPerSquareMeter); + return AsBaseUnitKilogramsPerSquareMeter().CompareTo(other.AsBaseUnitKilogramsPerSquareMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(AreaDensity left, AreaDensity right) { - return left._kilogramsPerSquareMeter <= right._kilogramsPerSquareMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(AreaDensity left, AreaDensity right) { - return left._kilogramsPerSquareMeter >= right._kilogramsPerSquareMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(AreaDensity left, AreaDensity right) { - return left._kilogramsPerSquareMeter < right._kilogramsPerSquareMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(AreaDensity left, AreaDensity right) { - return left._kilogramsPerSquareMeter > right._kilogramsPerSquareMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(AreaDensity left, AreaDensity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerSquareMeter == right._kilogramsPerSquareMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(AreaDensity left, AreaDensity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerSquareMeter != right._kilogramsPerSquareMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _kilogramsPerSquareMeter.Equals(((AreaDensity) obj)._kilogramsPerSquareMeter); + return AsBaseUnitKilogramsPerSquareMeter().Equals(((AreaDensity) obj).AsBaseUnitKilogramsPerSquareMeter()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(AreaDensity other, AreaDensity maxError) { - return Math.Abs(_kilogramsPerSquareMeter - other._kilogramsPerSquareMeter) <= maxError._kilogramsPerSquareMeter; + return Math.Abs(AsBaseUnitKilogramsPerSquareMeter() - other.AsBaseUnitKilogramsPerSquareMeter()) <= maxError.AsBaseUnitKilogramsPerSquareMeter(); } public override int GetHashCode() { - return _kilogramsPerSquareMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(AreaDensityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitKilogramsPerSquareMeter(); + switch (unit) { - case AreaDensityUnit.KilogramPerSquareMeter: - return KilogramsPerSquareMeter; + case AreaDensityUnit.KilogramPerSquareMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static AreaDensity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static AreaDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static AreaDensity Parse(string str, [CanBeNull] Culture culture) + public static AreaDensity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out AreaDensity result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out AreaDensity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out AreaDensity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static AreaDensityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static AreaDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static AreaDensityUnit ParseUnit(string str, [CanBeNull] string cultureNa /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static AreaDensityUnit ParseUnit(string str, [CanBeNull] string cultureNa #else public #endif - static AreaDensityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static AreaDensityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == AreaDensityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaDensityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static AreaDensityUnit ParseUnit(string str, IFormatProvider formatProvider = nu #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is KilogramPerSquareMeter /// @@ -587,7 +662,7 @@ static AreaDensityUnit ParseUnit(string str, IFormatProvider formatProvider = nu /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(AreaDensityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(AreaDensityUnit unit, [CanBeNull] Culture culture) + public string ToString( + AreaDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(AreaDensityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + AreaDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(AreaDensityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + AreaDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of AreaDensity /// - public static AreaDensity MaxValue - { - get - { - return new AreaDensity(double.MaxValue); - } - } + public static AreaDensity MaxValue => new AreaDensity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of AreaDensity /// - public static AreaDensity MinValue + public static AreaDensity MinValue => new AreaDensity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitKilogramsPerSquareMeter() { - get + if (Unit == AreaDensityUnit.KilogramPerSquareMeter) { return _value; } + + switch (Unit) { - return new AreaDensity(double.MinValue); - } - } - } + case AreaDensityUnit.KilogramPerSquareMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(AreaDensityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs index e0431b2112..b12c566c71 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct AreaMomentOfInertia : IComparable, IComparable - /// Base unit of AreaMomentOfInertia. + /// The numeric value this quantity was constructed with. /// - private readonly double _metersToTheFourth; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly AreaMomentOfInertiaUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public AreaMomentOfInertia() : this(0) + public AreaMomentOfInertia() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public AreaMomentOfInertia(double meterstothefourth) { - _metersToTheFourth = Convert.ToDouble(meterstothefourth); + _value = Convert.ToDouble(meterstothefourth); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + AreaMomentOfInertia(double numericValue, AreaMomentOfInertiaUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit MeterToTheFourth. + /// + /// Value assuming base unit MeterToTheFourth. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - AreaMomentOfInertia(long meterstothefourth) - { - _metersToTheFourth = Convert.ToDouble(meterstothefourth); - } + AreaMomentOfInertia(long meterstothefourth) : this(Convert.ToDouble(meterstothefourth), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit MeterToTheFourth. + /// + /// Value assuming base unit MeterToTheFourth. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - AreaMomentOfInertia(decimal meterstothefourth) - { - _metersToTheFourth = Convert.ToDouble(meterstothefourth); - } + AreaMomentOfInertia(decimal meterstothefourth) : this(Convert.ToDouble(meterstothefourth), BaseUnit) { } #region Properties @@ -119,72 +156,42 @@ public AreaMomentOfInertia(double meterstothefourth) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static AreaMomentOfInertiaUnit BaseUnit - { - get { return AreaMomentOfInertiaUnit.MeterToTheFourth; } - } + public static AreaMomentOfInertiaUnit BaseUnit => AreaMomentOfInertiaUnit.MeterToTheFourth; /// /// All units of measurement for the AreaMomentOfInertia quantity. /// public static AreaMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().ToArray(); - /// /// Get AreaMomentOfInertia in CentimetersToTheFourth. /// - public double CentimetersToTheFourth - { - get { return _metersToTheFourth*1e8; } - } - + public double CentimetersToTheFourth => As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); /// /// Get AreaMomentOfInertia in DecimetersToTheFourth. /// - public double DecimetersToTheFourth - { - get { return _metersToTheFourth*1e4; } - } - + public double DecimetersToTheFourth => As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); /// /// Get AreaMomentOfInertia in FeetToTheFourth. /// - public double FeetToTheFourth - { - get { return _metersToTheFourth/Math.Pow(0.3048, 4); } - } - + public double FeetToTheFourth => As(AreaMomentOfInertiaUnit.FootToTheFourth); /// /// Get AreaMomentOfInertia in InchesToTheFourth. /// - public double InchesToTheFourth - { - get { return _metersToTheFourth/Math.Pow(2.54e-2, 4); } - } - + public double InchesToTheFourth => As(AreaMomentOfInertiaUnit.InchToTheFourth); /// /// Get AreaMomentOfInertia in MetersToTheFourth. /// - public double MetersToTheFourth - { - get { return _metersToTheFourth; } - } - + public double MetersToTheFourth => As(AreaMomentOfInertiaUnit.MeterToTheFourth); /// /// Get AreaMomentOfInertia in MillimetersToTheFourth. /// - public double MillimetersToTheFourth - { - get { return _metersToTheFourth*1e12; } - } + public double MillimetersToTheFourth => As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); #endregion #region Static - public static AreaMomentOfInertia Zero - { - get { return new AreaMomentOfInertia(); } - } + public static AreaMomentOfInertia Zero => new AreaMomentOfInertia(0, BaseUnit); /// /// Get AreaMomentOfInertia from CentimetersToTheFourth. @@ -192,17 +199,13 @@ public static AreaMomentOfInertia Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AreaMomentOfInertia FromCentimetersToTheFourth(double centimeterstothefourth) - { - double value = (double) centimeterstothefourth; - return new AreaMomentOfInertia(value/1e8); - } #else public static AreaMomentOfInertia FromCentimetersToTheFourth(QuantityValue centimeterstothefourth) +#endif { double value = (double) centimeterstothefourth; - return new AreaMomentOfInertia((value/1e8)); + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); } -#endif /// /// Get AreaMomentOfInertia from DecimetersToTheFourth. @@ -210,17 +213,13 @@ public static AreaMomentOfInertia FromCentimetersToTheFourth(QuantityValue centi #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AreaMomentOfInertia FromDecimetersToTheFourth(double decimeterstothefourth) - { - double value = (double) decimeterstothefourth; - return new AreaMomentOfInertia(value/1e4); - } #else public static AreaMomentOfInertia FromDecimetersToTheFourth(QuantityValue decimeterstothefourth) +#endif { double value = (double) decimeterstothefourth; - return new AreaMomentOfInertia((value/1e4)); + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); } -#endif /// /// Get AreaMomentOfInertia from FeetToTheFourth. @@ -228,17 +227,13 @@ public static AreaMomentOfInertia FromDecimetersToTheFourth(QuantityValue decime #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AreaMomentOfInertia FromFeetToTheFourth(double feettothefourth) - { - double value = (double) feettothefourth; - return new AreaMomentOfInertia(value*Math.Pow(0.3048, 4)); - } #else public static AreaMomentOfInertia FromFeetToTheFourth(QuantityValue feettothefourth) +#endif { double value = (double) feettothefourth; - return new AreaMomentOfInertia((value*Math.Pow(0.3048, 4))); + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); } -#endif /// /// Get AreaMomentOfInertia from InchesToTheFourth. @@ -246,17 +241,13 @@ public static AreaMomentOfInertia FromFeetToTheFourth(QuantityValue feettothefou #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AreaMomentOfInertia FromInchesToTheFourth(double inchestothefourth) - { - double value = (double) inchestothefourth; - return new AreaMomentOfInertia(value*Math.Pow(2.54e-2, 4)); - } #else public static AreaMomentOfInertia FromInchesToTheFourth(QuantityValue inchestothefourth) +#endif { double value = (double) inchestothefourth; - return new AreaMomentOfInertia((value*Math.Pow(2.54e-2, 4))); + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); } -#endif /// /// Get AreaMomentOfInertia from MetersToTheFourth. @@ -264,17 +255,13 @@ public static AreaMomentOfInertia FromInchesToTheFourth(QuantityValue inchestoth #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AreaMomentOfInertia FromMetersToTheFourth(double meterstothefourth) - { - double value = (double) meterstothefourth; - return new AreaMomentOfInertia(value); - } #else public static AreaMomentOfInertia FromMetersToTheFourth(QuantityValue meterstothefourth) +#endif { double value = (double) meterstothefourth; - return new AreaMomentOfInertia((value)); + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); } -#endif /// /// Get AreaMomentOfInertia from MillimetersToTheFourth. @@ -282,17 +269,13 @@ public static AreaMomentOfInertia FromMetersToTheFourth(QuantityValue meterstoth #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static AreaMomentOfInertia FromMillimetersToTheFourth(double millimeterstothefourth) - { - double value = (double) millimeterstothefourth; - return new AreaMomentOfInertia(value/1e12); - } #else public static AreaMomentOfInertia FromMillimetersToTheFourth(QuantityValue millimeterstothefourth) +#endif { double value = (double) millimeterstothefourth; - return new AreaMomentOfInertia((value/1e12)); + return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MillimeterToTheFourth); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -402,24 +385,7 @@ public static AreaMomentOfInertia From(double value, AreaMomentOfInertiaUnit fro public static AreaMomentOfInertia From(QuantityValue value, AreaMomentOfInertiaUnit fromUnit) #endif { - switch (fromUnit) - { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: - return FromCentimetersToTheFourth(value); - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: - return FromDecimetersToTheFourth(value); - case AreaMomentOfInertiaUnit.FootToTheFourth: - return FromFeetToTheFourth(value); - case AreaMomentOfInertiaUnit.InchToTheFourth: - return FromInchesToTheFourth(value); - case AreaMomentOfInertiaUnit.MeterToTheFourth: - return FromMetersToTheFourth(value); - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: - return FromMillimetersToTheFourth(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new AreaMomentOfInertia((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -436,24 +402,8 @@ public static AreaMomentOfInertia From(QuantityValue value, AreaMomentOfInertiaU { return null; } - switch (fromUnit) - { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: - return FromCentimetersToTheFourth(value.Value); - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: - return FromDecimetersToTheFourth(value.Value); - case AreaMomentOfInertiaUnit.FootToTheFourth: - return FromFeetToTheFourth(value.Value); - case AreaMomentOfInertiaUnit.InchToTheFourth: - return FromInchesToTheFourth(value.Value); - case AreaMomentOfInertiaUnit.MeterToTheFourth: - return FromMetersToTheFourth(value.Value); - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: - return FromMillimetersToTheFourth(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new AreaMomentOfInertia((double)value.Value, fromUnit); } #endif @@ -472,12 +422,29 @@ public static string GetAbbreviation(AreaMomentOfInertiaUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + AreaMomentOfInertiaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -488,37 +455,37 @@ public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, [CanBeNull] C #if !WINDOWS_UWP public static AreaMomentOfInertia operator -(AreaMomentOfInertia right) { - return new AreaMomentOfInertia(-right._metersToTheFourth); + return new AreaMomentOfInertia(-right.Value, right.Unit); } public static AreaMomentOfInertia operator +(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return new AreaMomentOfInertia(left._metersToTheFourth + right._metersToTheFourth); + return new AreaMomentOfInertia(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static AreaMomentOfInertia operator -(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return new AreaMomentOfInertia(left._metersToTheFourth - right._metersToTheFourth); + return new AreaMomentOfInertia(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static AreaMomentOfInertia operator *(double left, AreaMomentOfInertia right) { - return new AreaMomentOfInertia(left*right._metersToTheFourth); + return new AreaMomentOfInertia(left * right.Value, right.Unit); } public static AreaMomentOfInertia operator *(AreaMomentOfInertia left, double right) { - return new AreaMomentOfInertia(left._metersToTheFourth*(double)right); + return new AreaMomentOfInertia(left.Value * right, left.Unit); } public static AreaMomentOfInertia operator /(AreaMomentOfInertia left, double right) { - return new AreaMomentOfInertia(left._metersToTheFourth/(double)right); + return new AreaMomentOfInertia(left.Value / right, left.Unit); } public static double operator /(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return Convert.ToDouble(left._metersToTheFourth/right._metersToTheFourth); + return left.MetersToTheFourth / right.MetersToTheFourth; } #endif @@ -541,43 +508,43 @@ public int CompareTo(object obj) #endif int CompareTo(AreaMomentOfInertia other) { - return _metersToTheFourth.CompareTo(other._metersToTheFourth); + return AsBaseUnitMetersToTheFourth().CompareTo(other.AsBaseUnitMetersToTheFourth()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return left._metersToTheFourth <= right._metersToTheFourth; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return left._metersToTheFourth >= right._metersToTheFourth; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return left._metersToTheFourth < right._metersToTheFourth; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return left._metersToTheFourth > right._metersToTheFourth; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(AreaMomentOfInertia left, AreaMomentOfInertia right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._metersToTheFourth == right._metersToTheFourth; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(AreaMomentOfInertia left, AreaMomentOfInertia right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._metersToTheFourth != right._metersToTheFourth; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -589,7 +556,7 @@ public override bool Equals(object obj) return false; } - return _metersToTheFourth.Equals(((AreaMomentOfInertia) obj)._metersToTheFourth); + return AsBaseUnitMetersToTheFourth().Equals(((AreaMomentOfInertia) obj).AsBaseUnitMetersToTheFourth()); } /// @@ -602,12 +569,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(AreaMomentOfInertia other, AreaMomentOfInertia maxError) { - return Math.Abs(_metersToTheFourth - other._metersToTheFourth) <= maxError._metersToTheFourth; + return Math.Abs(AsBaseUnitMetersToTheFourth() - other.AsBaseUnitMetersToTheFourth()) <= maxError.AsBaseUnitMetersToTheFourth(); } public override int GetHashCode() { - return _metersToTheFourth.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -617,24 +584,24 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(AreaMomentOfInertiaUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitMetersToTheFourth(); + switch (unit) { - case AreaMomentOfInertiaUnit.CentimeterToTheFourth: - return CentimetersToTheFourth; - case AreaMomentOfInertiaUnit.DecimeterToTheFourth: - return DecimetersToTheFourth; - case AreaMomentOfInertiaUnit.FootToTheFourth: - return FeetToTheFourth; - case AreaMomentOfInertiaUnit.InchToTheFourth: - return InchesToTheFourth; - case AreaMomentOfInertiaUnit.MeterToTheFourth: - return MetersToTheFourth; - case AreaMomentOfInertiaUnit.MillimeterToTheFourth: - return MillimetersToTheFourth; + case AreaMomentOfInertiaUnit.CentimeterToTheFourth: return baseUnitValue*1e8; + case AreaMomentOfInertiaUnit.DecimeterToTheFourth: return baseUnitValue*1e4; + case AreaMomentOfInertiaUnit.FootToTheFourth: return baseUnitValue/Math.Pow(0.3048, 4); + case AreaMomentOfInertiaUnit.InchToTheFourth: return baseUnitValue/Math.Pow(2.54e-2, 4); + case AreaMomentOfInertiaUnit.MeterToTheFourth: return baseUnitValue; + case AreaMomentOfInertiaUnit.MillimeterToTheFourth: return baseUnitValue*1e12; default: throw new NotImplementedException("unit: " + unit); @@ -676,7 +643,11 @@ public static AreaMomentOfInertia Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -695,17 +666,24 @@ public static AreaMomentOfInertia Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static AreaMomentOfInertia Parse(string str, [CanBeNull] Culture culture) + public static AreaMomentOfInertia Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -731,16 +709,41 @@ public static bool TryParse([CanBeNull] string str, out AreaMomentOfInertia resu /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out AreaMomentOfInertia result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out AreaMomentOfInertia result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -753,6 +756,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -766,11 +770,14 @@ public static AreaMomentOfInertiaUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static AreaMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -779,6 +786,8 @@ public static AreaMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string c /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -791,18 +800,18 @@ public static AreaMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string c #else public #endif - static AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == AreaMomentOfInertiaUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized AreaMomentOfInertiaUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -811,6 +820,7 @@ static AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider formatProvi #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is MeterToTheFourth /// @@ -822,7 +832,7 @@ static AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider formatProvi /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -839,74 +849,134 @@ public string ToString(AreaMomentOfInertiaUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(AreaMomentOfInertiaUnit unit, [CanBeNull] Culture culture) + public string ToString( + AreaMomentOfInertiaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(AreaMomentOfInertiaUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + AreaMomentOfInertiaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(AreaMomentOfInertiaUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + AreaMomentOfInertiaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of AreaMomentOfInertia /// - public static AreaMomentOfInertia MaxValue - { - get - { - return new AreaMomentOfInertia(double.MaxValue); - } - } + public static AreaMomentOfInertia MaxValue => new AreaMomentOfInertia(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of AreaMomentOfInertia /// - public static AreaMomentOfInertia MinValue + public static AreaMomentOfInertia MinValue => new AreaMomentOfInertia(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitMetersToTheFourth() { - get + if (Unit == AreaMomentOfInertiaUnit.MeterToTheFourth) { return _value; } + + switch (Unit) { - return new AreaMomentOfInertia(double.MinValue); - } - } - } + case AreaMomentOfInertiaUnit.CentimeterToTheFourth: return _value/1e8; + case AreaMomentOfInertiaUnit.DecimeterToTheFourth: return _value/1e4; + case AreaMomentOfInertiaUnit.FootToTheFourth: return _value*Math.Pow(0.3048, 4); + case AreaMomentOfInertiaUnit.InchToTheFourth: return _value*Math.Pow(2.54e-2, 4); + case AreaMomentOfInertiaUnit.MeterToTheFourth: return _value; + case AreaMomentOfInertiaUnit.MillimeterToTheFourth: return _value/1e12; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(AreaMomentOfInertiaUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs index fa8cd00cd6..a4785684ca 100644 --- a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct BitRate : IComparable, IComparable #endif { /// - /// Base unit of BitRate. + /// The numeric value this quantity was constructed with. + /// + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly decimal _bitsPerSecond; + private readonly BitRateUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public decimal Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public BitRate() : this(0) + public BitRate() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public BitRate(double bitspersecond) { - _bitsPerSecond = Convert.ToDecimal(bitspersecond); + _value = Convert.ToDecimal(bitspersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + BitRate(decimal numericValue, BitRateUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit BitPerSecond. + /// + /// Value assuming base unit BitPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - BitRate(long bitspersecond) - { - _bitsPerSecond = Convert.ToDecimal(bitspersecond); - } + BitRate(long bitspersecond) : this(Convert.ToDecimal(bitspersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit BitPerSecond. + /// + /// Value assuming base unit BitPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - BitRate(decimal bitspersecond) - { - _bitsPerSecond = Convert.ToDecimal(bitspersecond); - } + BitRate(decimal bitspersecond) : this(Convert.ToDecimal(bitspersecond), BaseUnit) { } #region Properties @@ -119,232 +156,122 @@ public BitRate(double bitspersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static BitRateUnit BaseUnit - { - get { return BitRateUnit.BitPerSecond; } - } + public static BitRateUnit BaseUnit => BitRateUnit.BitPerSecond; /// /// All units of measurement for the BitRate quantity. /// public static BitRateUnit[] Units { get; } = Enum.GetValues(typeof(BitRateUnit)).Cast().ToArray(); - /// /// Get BitRate in BitsPerSecond. /// - public double BitsPerSecond - { - get { return Convert.ToDouble(_bitsPerSecond); } - } - + public double BitsPerSecond => As(BitRateUnit.BitPerSecond); /// /// Get BitRate in BytesPerSecond. /// - public double BytesPerSecond - { - get { return Convert.ToDouble(_bitsPerSecond/8m); } - } - + public double BytesPerSecond => As(BitRateUnit.BytePerSecond); /// /// Get BitRate in ExabitsPerSecond. /// - public double ExabitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / 1e18m); } - } - + public double ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); /// /// Get BitRate in ExabytesPerSecond. /// - public double ExabytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / 1e18m); } - } - + public double ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); /// /// Get BitRate in ExbibitsPerSecond. /// - public double ExbibitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); } - } - + public double ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); /// /// Get BitRate in ExbibytesPerSecond. /// - public double ExbibytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); } - } - + public double ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); /// /// Get BitRate in GibibitsPerSecond. /// - public double GibibitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / (1024m * 1024 * 1024)); } - } - + public double GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); /// /// Get BitRate in GibibytesPerSecond. /// - public double GibibytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / (1024m * 1024 * 1024)); } - } - + public double GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); /// /// Get BitRate in GigabitsPerSecond. /// - public double GigabitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / 1e9m); } - } - + public double GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); /// /// Get BitRate in GigabytesPerSecond. /// - public double GigabytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / 1e9m); } - } - + public double GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); /// /// Get BitRate in KibibitsPerSecond. /// - public double KibibitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / 1024m); } - } - + public double KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); /// /// Get BitRate in KibibytesPerSecond. /// - public double KibibytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / 1024m); } - } - + public double KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); /// /// Get BitRate in KilobitsPerSecond. /// - public double KilobitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / 1e3m); } - } - + public double KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); /// /// Get BitRate in KilobytesPerSecond. /// - public double KilobytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / 1e3m); } - } - + public double KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); /// /// Get BitRate in MebibitsPerSecond. /// - public double MebibitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / (1024m * 1024)); } - } - + public double MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); /// /// Get BitRate in MebibytesPerSecond. /// - public double MebibytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / (1024m * 1024)); } - } - + public double MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); /// /// Get BitRate in MegabitsPerSecond. /// - public double MegabitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / 1e6m); } - } - + public double MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); /// /// Get BitRate in MegabytesPerSecond. /// - public double MegabytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / 1e6m); } - } - + public double MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); /// /// Get BitRate in PebibitsPerSecond. /// - public double PebibitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / (1024m * 1024 * 1024 * 1024 * 1024)); } - } - + public double PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); /// /// Get BitRate in PebibytesPerSecond. /// - public double PebibytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / (1024m * 1024 * 1024 * 1024 * 1024)); } - } - + public double PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); /// /// Get BitRate in PetabitsPerSecond. /// - public double PetabitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / 1e15m); } - } - + public double PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); /// /// Get BitRate in PetabytesPerSecond. /// - public double PetabytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / 1e15m); } - } - + public double PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); /// /// Get BitRate in TebibitsPerSecond. /// - public double TebibitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / (1024m * 1024 * 1024 * 1024)); } - } - + public double TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); /// /// Get BitRate in TebibytesPerSecond. /// - public double TebibytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / (1024m * 1024 * 1024 * 1024)); } - } - + public double TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); /// /// Get BitRate in TerabitsPerSecond. /// - public double TerabitsPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond) / 1e12m); } - } - + public double TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); /// /// Get BitRate in TerabytesPerSecond. /// - public double TerabytesPerSecond - { - get { return Convert.ToDouble((_bitsPerSecond/8m) / 1e12m); } - } + public double TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); #endregion #region Static - public static BitRate Zero - { - get { return new BitRate(); } - } + public static BitRate Zero => new BitRate(0, BaseUnit); /// /// Get BitRate from BitsPerSecond. @@ -352,17 +279,13 @@ public static BitRate Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromBitsPerSecond(double bitspersecond) - { - double value = (double) bitspersecond; - return new BitRate(Convert.ToDecimal(value)); - } #else public static BitRate FromBitsPerSecond(QuantityValue bitspersecond) +#endif { - double value = (double) bitspersecond; - return new BitRate((Convert.ToDecimal(value))); + decimal value = (decimal) bitspersecond; + return new BitRate(value, BitRateUnit.BitPerSecond); } -#endif /// /// Get BitRate from BytesPerSecond. @@ -370,17 +293,13 @@ public static BitRate FromBitsPerSecond(QuantityValue bitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromBytesPerSecond(double bytespersecond) - { - double value = (double) bytespersecond; - return new BitRate(Convert.ToDecimal(value*8d)); - } #else public static BitRate FromBytesPerSecond(QuantityValue bytespersecond) +#endif { - double value = (double) bytespersecond; - return new BitRate((Convert.ToDecimal(value*8d))); + decimal value = (decimal) bytespersecond; + return new BitRate(value, BitRateUnit.BytePerSecond); } -#endif /// /// Get BitRate from ExabitsPerSecond. @@ -388,17 +307,13 @@ public static BitRate FromBytesPerSecond(QuantityValue bytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromExabitsPerSecond(double exabitspersecond) - { - double value = (double) exabitspersecond; - return new BitRate(Convert.ToDecimal((value) * 1e18d)); - } #else public static BitRate FromExabitsPerSecond(QuantityValue exabitspersecond) +#endif { - double value = (double) exabitspersecond; - return new BitRate((Convert.ToDecimal((value) * 1e18d))); + decimal value = (decimal) exabitspersecond; + return new BitRate(value, BitRateUnit.ExabitPerSecond); } -#endif /// /// Get BitRate from ExabytesPerSecond. @@ -406,17 +321,13 @@ public static BitRate FromExabitsPerSecond(QuantityValue exabitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromExabytesPerSecond(double exabytespersecond) - { - double value = (double) exabytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * 1e18d)); - } #else public static BitRate FromExabytesPerSecond(QuantityValue exabytespersecond) +#endif { - double value = (double) exabytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * 1e18d))); + decimal value = (decimal) exabytespersecond; + return new BitRate(value, BitRateUnit.ExabytePerSecond); } -#endif /// /// Get BitRate from ExbibitsPerSecond. @@ -424,17 +335,13 @@ public static BitRate FromExabytesPerSecond(QuantityValue exabytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromExbibitsPerSecond(double exbibitspersecond) - { - double value = (double) exbibitspersecond; - return new BitRate(Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024))); - } #else public static BitRate FromExbibitsPerSecond(QuantityValue exbibitspersecond) +#endif { - double value = (double) exbibitspersecond; - return new BitRate((Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024)))); + decimal value = (decimal) exbibitspersecond; + return new BitRate(value, BitRateUnit.ExbibitPerSecond); } -#endif /// /// Get BitRate from ExbibytesPerSecond. @@ -442,17 +349,13 @@ public static BitRate FromExbibitsPerSecond(QuantityValue exbibitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromExbibytesPerSecond(double exbibytespersecond) - { - double value = (double) exbibytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024))); - } #else public static BitRate FromExbibytesPerSecond(QuantityValue exbibytespersecond) +#endif { - double value = (double) exbibytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024)))); + decimal value = (decimal) exbibytespersecond; + return new BitRate(value, BitRateUnit.ExbibytePerSecond); } -#endif /// /// Get BitRate from GibibitsPerSecond. @@ -460,17 +363,13 @@ public static BitRate FromExbibytesPerSecond(QuantityValue exbibytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromGibibitsPerSecond(double gibibitspersecond) - { - double value = (double) gibibitspersecond; - return new BitRate(Convert.ToDecimal((value) * (1024d * 1024 * 1024))); - } #else public static BitRate FromGibibitsPerSecond(QuantityValue gibibitspersecond) +#endif { - double value = (double) gibibitspersecond; - return new BitRate((Convert.ToDecimal((value) * (1024d * 1024 * 1024)))); + decimal value = (decimal) gibibitspersecond; + return new BitRate(value, BitRateUnit.GibibitPerSecond); } -#endif /// /// Get BitRate from GibibytesPerSecond. @@ -478,17 +377,13 @@ public static BitRate FromGibibitsPerSecond(QuantityValue gibibitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromGibibytesPerSecond(double gibibytespersecond) - { - double value = (double) gibibytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024))); - } #else public static BitRate FromGibibytesPerSecond(QuantityValue gibibytespersecond) +#endif { - double value = (double) gibibytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024)))); + decimal value = (decimal) gibibytespersecond; + return new BitRate(value, BitRateUnit.GibibytePerSecond); } -#endif /// /// Get BitRate from GigabitsPerSecond. @@ -496,17 +391,13 @@ public static BitRate FromGibibytesPerSecond(QuantityValue gibibytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromGigabitsPerSecond(double gigabitspersecond) - { - double value = (double) gigabitspersecond; - return new BitRate(Convert.ToDecimal((value) * 1e9d)); - } #else public static BitRate FromGigabitsPerSecond(QuantityValue gigabitspersecond) +#endif { - double value = (double) gigabitspersecond; - return new BitRate((Convert.ToDecimal((value) * 1e9d))); + decimal value = (decimal) gigabitspersecond; + return new BitRate(value, BitRateUnit.GigabitPerSecond); } -#endif /// /// Get BitRate from GigabytesPerSecond. @@ -514,17 +405,13 @@ public static BitRate FromGigabitsPerSecond(QuantityValue gigabitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromGigabytesPerSecond(double gigabytespersecond) - { - double value = (double) gigabytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * 1e9d)); - } #else public static BitRate FromGigabytesPerSecond(QuantityValue gigabytespersecond) +#endif { - double value = (double) gigabytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * 1e9d))); + decimal value = (decimal) gigabytespersecond; + return new BitRate(value, BitRateUnit.GigabytePerSecond); } -#endif /// /// Get BitRate from KibibitsPerSecond. @@ -532,17 +419,13 @@ public static BitRate FromGigabytesPerSecond(QuantityValue gigabytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromKibibitsPerSecond(double kibibitspersecond) - { - double value = (double) kibibitspersecond; - return new BitRate(Convert.ToDecimal((value) * 1024d)); - } #else public static BitRate FromKibibitsPerSecond(QuantityValue kibibitspersecond) +#endif { - double value = (double) kibibitspersecond; - return new BitRate((Convert.ToDecimal((value) * 1024d))); + decimal value = (decimal) kibibitspersecond; + return new BitRate(value, BitRateUnit.KibibitPerSecond); } -#endif /// /// Get BitRate from KibibytesPerSecond. @@ -550,17 +433,13 @@ public static BitRate FromKibibitsPerSecond(QuantityValue kibibitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromKibibytesPerSecond(double kibibytespersecond) - { - double value = (double) kibibytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * 1024d)); - } #else public static BitRate FromKibibytesPerSecond(QuantityValue kibibytespersecond) +#endif { - double value = (double) kibibytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * 1024d))); + decimal value = (decimal) kibibytespersecond; + return new BitRate(value, BitRateUnit.KibibytePerSecond); } -#endif /// /// Get BitRate from KilobitsPerSecond. @@ -568,17 +447,13 @@ public static BitRate FromKibibytesPerSecond(QuantityValue kibibytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromKilobitsPerSecond(double kilobitspersecond) - { - double value = (double) kilobitspersecond; - return new BitRate(Convert.ToDecimal((value) * 1e3d)); - } #else public static BitRate FromKilobitsPerSecond(QuantityValue kilobitspersecond) +#endif { - double value = (double) kilobitspersecond; - return new BitRate((Convert.ToDecimal((value) * 1e3d))); + decimal value = (decimal) kilobitspersecond; + return new BitRate(value, BitRateUnit.KilobitPerSecond); } -#endif /// /// Get BitRate from KilobytesPerSecond. @@ -586,17 +461,13 @@ public static BitRate FromKilobitsPerSecond(QuantityValue kilobitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromKilobytesPerSecond(double kilobytespersecond) - { - double value = (double) kilobytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * 1e3d)); - } #else public static BitRate FromKilobytesPerSecond(QuantityValue kilobytespersecond) +#endif { - double value = (double) kilobytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * 1e3d))); + decimal value = (decimal) kilobytespersecond; + return new BitRate(value, BitRateUnit.KilobytePerSecond); } -#endif /// /// Get BitRate from MebibitsPerSecond. @@ -604,17 +475,13 @@ public static BitRate FromKilobytesPerSecond(QuantityValue kilobytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromMebibitsPerSecond(double mebibitspersecond) - { - double value = (double) mebibitspersecond; - return new BitRate(Convert.ToDecimal((value) * (1024d * 1024))); - } #else public static BitRate FromMebibitsPerSecond(QuantityValue mebibitspersecond) +#endif { - double value = (double) mebibitspersecond; - return new BitRate((Convert.ToDecimal((value) * (1024d * 1024)))); + decimal value = (decimal) mebibitspersecond; + return new BitRate(value, BitRateUnit.MebibitPerSecond); } -#endif /// /// Get BitRate from MebibytesPerSecond. @@ -622,17 +489,13 @@ public static BitRate FromMebibitsPerSecond(QuantityValue mebibitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromMebibytesPerSecond(double mebibytespersecond) - { - double value = (double) mebibytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * (1024d * 1024))); - } #else public static BitRate FromMebibytesPerSecond(QuantityValue mebibytespersecond) +#endif { - double value = (double) mebibytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * (1024d * 1024)))); + decimal value = (decimal) mebibytespersecond; + return new BitRate(value, BitRateUnit.MebibytePerSecond); } -#endif /// /// Get BitRate from MegabitsPerSecond. @@ -640,17 +503,13 @@ public static BitRate FromMebibytesPerSecond(QuantityValue mebibytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromMegabitsPerSecond(double megabitspersecond) - { - double value = (double) megabitspersecond; - return new BitRate(Convert.ToDecimal((value) * 1e6d)); - } #else public static BitRate FromMegabitsPerSecond(QuantityValue megabitspersecond) +#endif { - double value = (double) megabitspersecond; - return new BitRate((Convert.ToDecimal((value) * 1e6d))); + decimal value = (decimal) megabitspersecond; + return new BitRate(value, BitRateUnit.MegabitPerSecond); } -#endif /// /// Get BitRate from MegabytesPerSecond. @@ -658,17 +517,13 @@ public static BitRate FromMegabitsPerSecond(QuantityValue megabitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromMegabytesPerSecond(double megabytespersecond) - { - double value = (double) megabytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * 1e6d)); - } #else public static BitRate FromMegabytesPerSecond(QuantityValue megabytespersecond) +#endif { - double value = (double) megabytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * 1e6d))); + decimal value = (decimal) megabytespersecond; + return new BitRate(value, BitRateUnit.MegabytePerSecond); } -#endif /// /// Get BitRate from PebibitsPerSecond. @@ -676,17 +531,13 @@ public static BitRate FromMegabytesPerSecond(QuantityValue megabytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromPebibitsPerSecond(double pebibitspersecond) - { - double value = (double) pebibitspersecond; - return new BitRate(Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024 * 1024))); - } #else public static BitRate FromPebibitsPerSecond(QuantityValue pebibitspersecond) +#endif { - double value = (double) pebibitspersecond; - return new BitRate((Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024 * 1024)))); + decimal value = (decimal) pebibitspersecond; + return new BitRate(value, BitRateUnit.PebibitPerSecond); } -#endif /// /// Get BitRate from PebibytesPerSecond. @@ -694,17 +545,13 @@ public static BitRate FromPebibitsPerSecond(QuantityValue pebibitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromPebibytesPerSecond(double pebibytespersecond) - { - double value = (double) pebibytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024 * 1024))); - } #else public static BitRate FromPebibytesPerSecond(QuantityValue pebibytespersecond) +#endif { - double value = (double) pebibytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024 * 1024)))); + decimal value = (decimal) pebibytespersecond; + return new BitRate(value, BitRateUnit.PebibytePerSecond); } -#endif /// /// Get BitRate from PetabitsPerSecond. @@ -712,17 +559,13 @@ public static BitRate FromPebibytesPerSecond(QuantityValue pebibytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromPetabitsPerSecond(double petabitspersecond) - { - double value = (double) petabitspersecond; - return new BitRate(Convert.ToDecimal((value) * 1e15d)); - } #else public static BitRate FromPetabitsPerSecond(QuantityValue petabitspersecond) +#endif { - double value = (double) petabitspersecond; - return new BitRate((Convert.ToDecimal((value) * 1e15d))); + decimal value = (decimal) petabitspersecond; + return new BitRate(value, BitRateUnit.PetabitPerSecond); } -#endif /// /// Get BitRate from PetabytesPerSecond. @@ -730,17 +573,13 @@ public static BitRate FromPetabitsPerSecond(QuantityValue petabitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromPetabytesPerSecond(double petabytespersecond) - { - double value = (double) petabytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * 1e15d)); - } #else public static BitRate FromPetabytesPerSecond(QuantityValue petabytespersecond) +#endif { - double value = (double) petabytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * 1e15d))); + decimal value = (decimal) petabytespersecond; + return new BitRate(value, BitRateUnit.PetabytePerSecond); } -#endif /// /// Get BitRate from TebibitsPerSecond. @@ -748,17 +587,13 @@ public static BitRate FromPetabytesPerSecond(QuantityValue petabytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromTebibitsPerSecond(double tebibitspersecond) - { - double value = (double) tebibitspersecond; - return new BitRate(Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024))); - } #else public static BitRate FromTebibitsPerSecond(QuantityValue tebibitspersecond) +#endif { - double value = (double) tebibitspersecond; - return new BitRate((Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024)))); + decimal value = (decimal) tebibitspersecond; + return new BitRate(value, BitRateUnit.TebibitPerSecond); } -#endif /// /// Get BitRate from TebibytesPerSecond. @@ -766,17 +601,13 @@ public static BitRate FromTebibitsPerSecond(QuantityValue tebibitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromTebibytesPerSecond(double tebibytespersecond) - { - double value = (double) tebibytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024))); - } #else public static BitRate FromTebibytesPerSecond(QuantityValue tebibytespersecond) +#endif { - double value = (double) tebibytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024)))); + decimal value = (decimal) tebibytespersecond; + return new BitRate(value, BitRateUnit.TebibytePerSecond); } -#endif /// /// Get BitRate from TerabitsPerSecond. @@ -784,17 +615,13 @@ public static BitRate FromTebibytesPerSecond(QuantityValue tebibytespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromTerabitsPerSecond(double terabitspersecond) - { - double value = (double) terabitspersecond; - return new BitRate(Convert.ToDecimal((value) * 1e12d)); - } #else public static BitRate FromTerabitsPerSecond(QuantityValue terabitspersecond) +#endif { - double value = (double) terabitspersecond; - return new BitRate((Convert.ToDecimal((value) * 1e12d))); + decimal value = (decimal) terabitspersecond; + return new BitRate(value, BitRateUnit.TerabitPerSecond); } -#endif /// /// Get BitRate from TerabytesPerSecond. @@ -802,17 +629,13 @@ public static BitRate FromTerabitsPerSecond(QuantityValue terabitspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BitRate FromTerabytesPerSecond(double terabytespersecond) - { - double value = (double) terabytespersecond; - return new BitRate(Convert.ToDecimal((value*8d) * 1e12d)); - } #else public static BitRate FromTerabytesPerSecond(QuantityValue terabytespersecond) +#endif { - double value = (double) terabytespersecond; - return new BitRate((Convert.ToDecimal((value*8d) * 1e12d))); + decimal value = (decimal) terabytespersecond; + return new BitRate(value, BitRateUnit.TerabytePerSecond); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1222,64 +1045,7 @@ public static BitRate From(double value, BitRateUnit fromUnit) public static BitRate From(QuantityValue value, BitRateUnit fromUnit) #endif { - switch (fromUnit) - { - case BitRateUnit.BitPerSecond: - return FromBitsPerSecond(value); - case BitRateUnit.BytePerSecond: - return FromBytesPerSecond(value); - case BitRateUnit.ExabitPerSecond: - return FromExabitsPerSecond(value); - case BitRateUnit.ExabytePerSecond: - return FromExabytesPerSecond(value); - case BitRateUnit.ExbibitPerSecond: - return FromExbibitsPerSecond(value); - case BitRateUnit.ExbibytePerSecond: - return FromExbibytesPerSecond(value); - case BitRateUnit.GibibitPerSecond: - return FromGibibitsPerSecond(value); - case BitRateUnit.GibibytePerSecond: - return FromGibibytesPerSecond(value); - case BitRateUnit.GigabitPerSecond: - return FromGigabitsPerSecond(value); - case BitRateUnit.GigabytePerSecond: - return FromGigabytesPerSecond(value); - case BitRateUnit.KibibitPerSecond: - return FromKibibitsPerSecond(value); - case BitRateUnit.KibibytePerSecond: - return FromKibibytesPerSecond(value); - case BitRateUnit.KilobitPerSecond: - return FromKilobitsPerSecond(value); - case BitRateUnit.KilobytePerSecond: - return FromKilobytesPerSecond(value); - case BitRateUnit.MebibitPerSecond: - return FromMebibitsPerSecond(value); - case BitRateUnit.MebibytePerSecond: - return FromMebibytesPerSecond(value); - case BitRateUnit.MegabitPerSecond: - return FromMegabitsPerSecond(value); - case BitRateUnit.MegabytePerSecond: - return FromMegabytesPerSecond(value); - case BitRateUnit.PebibitPerSecond: - return FromPebibitsPerSecond(value); - case BitRateUnit.PebibytePerSecond: - return FromPebibytesPerSecond(value); - case BitRateUnit.PetabitPerSecond: - return FromPetabitsPerSecond(value); - case BitRateUnit.PetabytePerSecond: - return FromPetabytesPerSecond(value); - case BitRateUnit.TebibitPerSecond: - return FromTebibitsPerSecond(value); - case BitRateUnit.TebibytePerSecond: - return FromTebibytesPerSecond(value); - case BitRateUnit.TerabitPerSecond: - return FromTerabitsPerSecond(value); - case BitRateUnit.TerabytePerSecond: - return FromTerabytesPerSecond(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new BitRate((decimal)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1296,64 +1062,8 @@ public static BitRate From(QuantityValue value, BitRateUnit fromUnit) { return null; } - switch (fromUnit) - { - case BitRateUnit.BitPerSecond: - return FromBitsPerSecond(value.Value); - case BitRateUnit.BytePerSecond: - return FromBytesPerSecond(value.Value); - case BitRateUnit.ExabitPerSecond: - return FromExabitsPerSecond(value.Value); - case BitRateUnit.ExabytePerSecond: - return FromExabytesPerSecond(value.Value); - case BitRateUnit.ExbibitPerSecond: - return FromExbibitsPerSecond(value.Value); - case BitRateUnit.ExbibytePerSecond: - return FromExbibytesPerSecond(value.Value); - case BitRateUnit.GibibitPerSecond: - return FromGibibitsPerSecond(value.Value); - case BitRateUnit.GibibytePerSecond: - return FromGibibytesPerSecond(value.Value); - case BitRateUnit.GigabitPerSecond: - return FromGigabitsPerSecond(value.Value); - case BitRateUnit.GigabytePerSecond: - return FromGigabytesPerSecond(value.Value); - case BitRateUnit.KibibitPerSecond: - return FromKibibitsPerSecond(value.Value); - case BitRateUnit.KibibytePerSecond: - return FromKibibytesPerSecond(value.Value); - case BitRateUnit.KilobitPerSecond: - return FromKilobitsPerSecond(value.Value); - case BitRateUnit.KilobytePerSecond: - return FromKilobytesPerSecond(value.Value); - case BitRateUnit.MebibitPerSecond: - return FromMebibitsPerSecond(value.Value); - case BitRateUnit.MebibytePerSecond: - return FromMebibytesPerSecond(value.Value); - case BitRateUnit.MegabitPerSecond: - return FromMegabitsPerSecond(value.Value); - case BitRateUnit.MegabytePerSecond: - return FromMegabytesPerSecond(value.Value); - case BitRateUnit.PebibitPerSecond: - return FromPebibitsPerSecond(value.Value); - case BitRateUnit.PebibytePerSecond: - return FromPebibytesPerSecond(value.Value); - case BitRateUnit.PetabitPerSecond: - return FromPetabitsPerSecond(value.Value); - case BitRateUnit.PetabytePerSecond: - return FromPetabytesPerSecond(value.Value); - case BitRateUnit.TebibitPerSecond: - return FromTebibitsPerSecond(value.Value); - case BitRateUnit.TebibytePerSecond: - return FromTebibytesPerSecond(value.Value); - case BitRateUnit.TerabitPerSecond: - return FromTerabitsPerSecond(value.Value); - case BitRateUnit.TerabytePerSecond: - return FromTerabytesPerSecond(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new BitRate((decimal)value.Value, fromUnit); } #endif @@ -1372,12 +1082,29 @@ public static string GetAbbreviation(BitRateUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(BitRateUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + BitRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1388,37 +1115,37 @@ public static string GetAbbreviation(BitRateUnit unit, [CanBeNull] Culture cultu #if !WINDOWS_UWP public static BitRate operator -(BitRate right) { - return new BitRate(-right._bitsPerSecond); + return new BitRate(-right.Value, right.Unit); } public static BitRate operator +(BitRate left, BitRate right) { - return new BitRate(left._bitsPerSecond + right._bitsPerSecond); + return new BitRate(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static BitRate operator -(BitRate left, BitRate right) { - return new BitRate(left._bitsPerSecond - right._bitsPerSecond); + return new BitRate(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static BitRate operator *(decimal left, BitRate right) { - return new BitRate(left*right._bitsPerSecond); + return new BitRate(left * right.Value, right.Unit); } - public static BitRate operator *(BitRate left, double right) + public static BitRate operator *(BitRate left, decimal right) { - return new BitRate(left._bitsPerSecond*(decimal)right); + return new BitRate(left.Value * right, left.Unit); } - public static BitRate operator /(BitRate left, double right) + public static BitRate operator /(BitRate left, decimal right) { - return new BitRate(left._bitsPerSecond/(decimal)right); + return new BitRate(left.Value / right, left.Unit); } public static double operator /(BitRate left, BitRate right) { - return Convert.ToDouble(left._bitsPerSecond/right._bitsPerSecond); + return left.BitsPerSecond / right.BitsPerSecond; } #endif @@ -1441,41 +1168,41 @@ public int CompareTo(object obj) #endif int CompareTo(BitRate other) { - return _bitsPerSecond.CompareTo(other._bitsPerSecond); + return AsBaseUnitBitsPerSecond().CompareTo(other.AsBaseUnitBitsPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(BitRate left, BitRate right) { - return left._bitsPerSecond <= right._bitsPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(BitRate left, BitRate right) { - return left._bitsPerSecond >= right._bitsPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(BitRate left, BitRate right) { - return left._bitsPerSecond < right._bitsPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(BitRate left, BitRate right) { - return left._bitsPerSecond > right._bitsPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } public static bool operator ==(BitRate left, BitRate right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._bitsPerSecond == right._bitsPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } public static bool operator !=(BitRate left, BitRate right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._bitsPerSecond != right._bitsPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1486,7 +1213,7 @@ public override bool Equals(object obj) return false; } - return _bitsPerSecond.Equals(((BitRate) obj)._bitsPerSecond); + return AsBaseUnitBitsPerSecond().Equals(((BitRate) obj).AsBaseUnitBitsPerSecond()); } /// @@ -1499,12 +1226,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(BitRate other, BitRate maxError) { - return Math.Abs(_bitsPerSecond - other._bitsPerSecond) <= maxError._bitsPerSecond; + return Math.Abs(AsBaseUnitBitsPerSecond() - other.AsBaseUnitBitsPerSecond()) <= maxError.AsBaseUnitBitsPerSecond(); } public override int GetHashCode() { - return _bitsPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1514,64 +1241,44 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(BitRateUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + decimal baseUnitValue = AsBaseUnitBitsPerSecond(); + switch (unit) { - case BitRateUnit.BitPerSecond: - return BitsPerSecond; - case BitRateUnit.BytePerSecond: - return BytesPerSecond; - case BitRateUnit.ExabitPerSecond: - return ExabitsPerSecond; - case BitRateUnit.ExabytePerSecond: - return ExabytesPerSecond; - case BitRateUnit.ExbibitPerSecond: - return ExbibitsPerSecond; - case BitRateUnit.ExbibytePerSecond: - return ExbibytesPerSecond; - case BitRateUnit.GibibitPerSecond: - return GibibitsPerSecond; - case BitRateUnit.GibibytePerSecond: - return GibibytesPerSecond; - case BitRateUnit.GigabitPerSecond: - return GigabitsPerSecond; - case BitRateUnit.GigabytePerSecond: - return GigabytesPerSecond; - case BitRateUnit.KibibitPerSecond: - return KibibitsPerSecond; - case BitRateUnit.KibibytePerSecond: - return KibibytesPerSecond; - case BitRateUnit.KilobitPerSecond: - return KilobitsPerSecond; - case BitRateUnit.KilobytePerSecond: - return KilobytesPerSecond; - case BitRateUnit.MebibitPerSecond: - return MebibitsPerSecond; - case BitRateUnit.MebibytePerSecond: - return MebibytesPerSecond; - case BitRateUnit.MegabitPerSecond: - return MegabitsPerSecond; - case BitRateUnit.MegabytePerSecond: - return MegabytesPerSecond; - case BitRateUnit.PebibitPerSecond: - return PebibitsPerSecond; - case BitRateUnit.PebibytePerSecond: - return PebibytesPerSecond; - case BitRateUnit.PetabitPerSecond: - return PetabitsPerSecond; - case BitRateUnit.PetabytePerSecond: - return PetabytesPerSecond; - case BitRateUnit.TebibitPerSecond: - return TebibitsPerSecond; - case BitRateUnit.TebibytePerSecond: - return TebibytesPerSecond; - case BitRateUnit.TerabitPerSecond: - return TerabitsPerSecond; - case BitRateUnit.TerabytePerSecond: - return TerabytesPerSecond; + case BitRateUnit.BitPerSecond: return Convert.ToDouble(baseUnitValue); + case BitRateUnit.BytePerSecond: return Convert.ToDouble(baseUnitValue/8m); + case BitRateUnit.ExabitPerSecond: return Convert.ToDouble((baseUnitValue) / 1e18m); + case BitRateUnit.ExabytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / 1e18m); + case BitRateUnit.ExbibitPerSecond: return Convert.ToDouble((baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); + case BitRateUnit.ExbibytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); + case BitRateUnit.GibibitPerSecond: return Convert.ToDouble((baseUnitValue) / (1024m * 1024 * 1024)); + case BitRateUnit.GibibytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / (1024m * 1024 * 1024)); + case BitRateUnit.GigabitPerSecond: return Convert.ToDouble((baseUnitValue) / 1e9m); + case BitRateUnit.GigabytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / 1e9m); + case BitRateUnit.KibibitPerSecond: return Convert.ToDouble((baseUnitValue) / 1024m); + case BitRateUnit.KibibytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / 1024m); + case BitRateUnit.KilobitPerSecond: return Convert.ToDouble((baseUnitValue) / 1e3m); + case BitRateUnit.KilobytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / 1e3m); + case BitRateUnit.MebibitPerSecond: return Convert.ToDouble((baseUnitValue) / (1024m * 1024)); + case BitRateUnit.MebibytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / (1024m * 1024)); + case BitRateUnit.MegabitPerSecond: return Convert.ToDouble((baseUnitValue) / 1e6m); + case BitRateUnit.MegabytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / 1e6m); + case BitRateUnit.PebibitPerSecond: return Convert.ToDouble((baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024)); + case BitRateUnit.PebibytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024)); + case BitRateUnit.PetabitPerSecond: return Convert.ToDouble((baseUnitValue) / 1e15m); + case BitRateUnit.PetabytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / 1e15m); + case BitRateUnit.TebibitPerSecond: return Convert.ToDouble((baseUnitValue) / (1024m * 1024 * 1024 * 1024)); + case BitRateUnit.TebibytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024)); + case BitRateUnit.TerabitPerSecond: return Convert.ToDouble((baseUnitValue) / 1e12m); + case BitRateUnit.TerabytePerSecond: return Convert.ToDouble((baseUnitValue/8m) / 1e12m); default: throw new NotImplementedException("unit: " + unit); @@ -1613,7 +1320,11 @@ public static BitRate Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1632,17 +1343,24 @@ public static BitRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static BitRate Parse(string str, [CanBeNull] Culture culture) + public static BitRate Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1668,16 +1386,41 @@ public static bool TryParse([CanBeNull] string str, out BitRate result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out BitRate result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out BitRate result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1690,6 +1433,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1703,11 +1447,14 @@ public static BitRateUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static BitRateUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1716,6 +1463,8 @@ public static BitRateUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1728,18 +1477,18 @@ public static BitRateUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static BitRateUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static BitRateUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == BitRateUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized BitRateUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1748,6 +1497,7 @@ static BitRateUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is BitPerSecond /// @@ -1759,7 +1509,7 @@ static BitRateUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1776,74 +1526,154 @@ public string ToString(BitRateUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(BitRateUnit unit, [CanBeNull] Culture culture) + public string ToString( + BitRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(BitRateUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + BitRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(BitRateUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + BitRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of BitRate /// - public static BitRate MaxValue - { - get - { - return new BitRate(decimal.MaxValue); - } - } + public static BitRate MaxValue => new BitRate(decimal.MaxValue, BaseUnit); /// /// Represents the smallest possible value of BitRate /// - public static BitRate MinValue + public static BitRate MinValue => new BitRate(decimal.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private decimal AsBaseUnitBitsPerSecond() { - get + if (Unit == BitRateUnit.BitPerSecond) { return _value; } + + switch (Unit) { - return new BitRate(decimal.MinValue); - } - } - } + case BitRateUnit.BitPerSecond: return Convert.ToDecimal(_value); + case BitRateUnit.BytePerSecond: return Convert.ToDecimal(_value*8m); + case BitRateUnit.ExabitPerSecond: return Convert.ToDecimal((_value) * 1e18m); + case BitRateUnit.ExabytePerSecond: return Convert.ToDecimal((_value*8m) * 1e18m); + case BitRateUnit.ExbibitPerSecond: return Convert.ToDecimal((_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); + case BitRateUnit.ExbibytePerSecond: return Convert.ToDecimal((_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); + case BitRateUnit.GibibitPerSecond: return Convert.ToDecimal((_value) * (1024m * 1024 * 1024)); + case BitRateUnit.GibibytePerSecond: return Convert.ToDecimal((_value*8m) * (1024m * 1024 * 1024)); + case BitRateUnit.GigabitPerSecond: return Convert.ToDecimal((_value) * 1e9m); + case BitRateUnit.GigabytePerSecond: return Convert.ToDecimal((_value*8m) * 1e9m); + case BitRateUnit.KibibitPerSecond: return Convert.ToDecimal((_value) * 1024m); + case BitRateUnit.KibibytePerSecond: return Convert.ToDecimal((_value*8m) * 1024m); + case BitRateUnit.KilobitPerSecond: return Convert.ToDecimal((_value) * 1e3m); + case BitRateUnit.KilobytePerSecond: return Convert.ToDecimal((_value*8m) * 1e3m); + case BitRateUnit.MebibitPerSecond: return Convert.ToDecimal((_value) * (1024m * 1024)); + case BitRateUnit.MebibytePerSecond: return Convert.ToDecimal((_value*8m) * (1024m * 1024)); + case BitRateUnit.MegabitPerSecond: return Convert.ToDecimal((_value) * 1e6m); + case BitRateUnit.MegabytePerSecond: return Convert.ToDecimal((_value*8m) * 1e6m); + case BitRateUnit.PebibitPerSecond: return Convert.ToDecimal((_value) * (1024m * 1024 * 1024 * 1024 * 1024)); + case BitRateUnit.PebibytePerSecond: return Convert.ToDecimal((_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024)); + case BitRateUnit.PetabitPerSecond: return Convert.ToDecimal((_value) * 1e15m); + case BitRateUnit.PetabytePerSecond: return Convert.ToDecimal((_value*8m) * 1e15m); + case BitRateUnit.TebibitPerSecond: return Convert.ToDecimal((_value) * (1024m * 1024 * 1024 * 1024)); + case BitRateUnit.TebibytePerSecond: return Convert.ToDecimal((_value*8m) * (1024m * 1024 * 1024 * 1024)); + case BitRateUnit.TerabitPerSecond: return Convert.ToDecimal((_value) * 1e12m); + case BitRateUnit.TerabytePerSecond: return Convert.ToDecimal((_value*8m) * 1e12m); + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private decimal AsBaseNumericType(BitRateUnit unit) => Convert.ToDecimal(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs index 40251e840f..c576221716 100644 --- a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct BrakeSpecificFuelConsumption : IComparable, IComparable
- /// Base unit of BrakeSpecificFuelConsumption. + /// The numeric value this quantity was constructed with. + ///
+ private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly BrakeSpecificFuelConsumptionUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _kilogramsPerJoule; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public BrakeSpecificFuelConsumption() : this(0) + public BrakeSpecificFuelConsumption() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public BrakeSpecificFuelConsumption(double kilogramsperjoule) { - _kilogramsPerJoule = Convert.ToDouble(kilogramsperjoule); + _value = Convert.ToDouble(kilogramsperjoule); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + BrakeSpecificFuelConsumption(double numericValue, BrakeSpecificFuelConsumptionUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerJoule. + /// + /// Value assuming base unit KilogramPerJoule. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - BrakeSpecificFuelConsumption(long kilogramsperjoule) - { - _kilogramsPerJoule = Convert.ToDouble(kilogramsperjoule); - } + BrakeSpecificFuelConsumption(long kilogramsperjoule) : this(Convert.ToDouble(kilogramsperjoule), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerJoule. + /// + /// Value assuming base unit KilogramPerJoule. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - BrakeSpecificFuelConsumption(decimal kilogramsperjoule) - { - _kilogramsPerJoule = Convert.ToDouble(kilogramsperjoule); - } + BrakeSpecificFuelConsumption(decimal kilogramsperjoule) : this(Convert.ToDouble(kilogramsperjoule), BaseUnit) { } #region Properties @@ -119,48 +156,30 @@ public BrakeSpecificFuelConsumption(double kilogramsperjoule) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static BrakeSpecificFuelConsumptionUnit BaseUnit - { - get { return BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; } - } + public static BrakeSpecificFuelConsumptionUnit BaseUnit => BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; /// /// All units of measurement for the BrakeSpecificFuelConsumption quantity. /// public static BrakeSpecificFuelConsumptionUnit[] Units { get; } = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().ToArray(); - /// /// Get BrakeSpecificFuelConsumption in GramsPerKiloWattHour. /// - public double GramsPerKiloWattHour - { - get { return _kilogramsPerJoule*3.6e9; } - } - + public double GramsPerKiloWattHour => As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); /// /// Get BrakeSpecificFuelConsumption in KilogramsPerJoule. /// - public double KilogramsPerJoule - { - get { return _kilogramsPerJoule; } - } - + public double KilogramsPerJoule => As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); /// /// Get BrakeSpecificFuelConsumption in PoundsPerMechanicalHorsepowerHour. /// - public double PoundsPerMechanicalHorsepowerHour - { - get { return _kilogramsPerJoule/1.689659410672e-7; } - } + public double PoundsPerMechanicalHorsepowerHour => As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); #endregion #region Static - public static BrakeSpecificFuelConsumption Zero - { - get { return new BrakeSpecificFuelConsumption(); } - } + public static BrakeSpecificFuelConsumption Zero => new BrakeSpecificFuelConsumption(0, BaseUnit); /// /// Get BrakeSpecificFuelConsumption from GramsPerKiloWattHour. @@ -168,17 +187,13 @@ public static BrakeSpecificFuelConsumption Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(double gramsperkilowatthour) - { - double value = (double) gramsperkilowatthour; - return new BrakeSpecificFuelConsumption(value/3.6e9); - } #else public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(QuantityValue gramsperkilowatthour) +#endif { double value = (double) gramsperkilowatthour; - return new BrakeSpecificFuelConsumption((value/3.6e9)); + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); } -#endif /// /// Get BrakeSpecificFuelConsumption from KilogramsPerJoule. @@ -186,17 +201,13 @@ public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(QuantityValu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(double kilogramsperjoule) - { - double value = (double) kilogramsperjoule; - return new BrakeSpecificFuelConsumption(value); - } #else public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(QuantityValue kilogramsperjoule) +#endif { double value = (double) kilogramsperjoule; - return new BrakeSpecificFuelConsumption((value)); + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); } -#endif /// /// Get BrakeSpecificFuelConsumption from PoundsPerMechanicalHorsepowerHour. @@ -204,17 +215,13 @@ public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(QuantityValue k #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(double poundspermechanicalhorsepowerhour) - { - double value = (double) poundspermechanicalhorsepowerhour; - return new BrakeSpecificFuelConsumption(value*1.689659410672e-7); - } #else public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(QuantityValue poundspermechanicalhorsepowerhour) +#endif { double value = (double) poundspermechanicalhorsepowerhour; - return new BrakeSpecificFuelConsumption((value*1.689659410672e-7)); + return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -279,18 +286,7 @@ public static BrakeSpecificFuelConsumption From(double value, BrakeSpecificFuelC public static BrakeSpecificFuelConsumption From(QuantityValue value, BrakeSpecificFuelConsumptionUnit fromUnit) #endif { - switch (fromUnit) - { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: - return FromGramsPerKiloWattHour(value); - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: - return FromKilogramsPerJoule(value); - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: - return FromPoundsPerMechanicalHorsepowerHour(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new BrakeSpecificFuelConsumption((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -307,18 +303,8 @@ public static BrakeSpecificFuelConsumption From(QuantityValue value, BrakeSpecif { return null; } - switch (fromUnit) - { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: - return FromGramsPerKiloWattHour(value.Value); - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: - return FromKilogramsPerJoule(value.Value); - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: - return FromPoundsPerMechanicalHorsepowerHour(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new BrakeSpecificFuelConsumption((double)value.Value, fromUnit); } #endif @@ -337,12 +323,29 @@ public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + BrakeSpecificFuelConsumptionUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -353,37 +356,37 @@ public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, [Can #if !WINDOWS_UWP public static BrakeSpecificFuelConsumption operator -(BrakeSpecificFuelConsumption right) { - return new BrakeSpecificFuelConsumption(-right._kilogramsPerJoule); + return new BrakeSpecificFuelConsumption(-right.Value, right.Unit); } public static BrakeSpecificFuelConsumption operator +(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return new BrakeSpecificFuelConsumption(left._kilogramsPerJoule + right._kilogramsPerJoule); + return new BrakeSpecificFuelConsumption(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static BrakeSpecificFuelConsumption operator -(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return new BrakeSpecificFuelConsumption(left._kilogramsPerJoule - right._kilogramsPerJoule); + return new BrakeSpecificFuelConsumption(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static BrakeSpecificFuelConsumption operator *(double left, BrakeSpecificFuelConsumption right) { - return new BrakeSpecificFuelConsumption(left*right._kilogramsPerJoule); + return new BrakeSpecificFuelConsumption(left * right.Value, right.Unit); } public static BrakeSpecificFuelConsumption operator *(BrakeSpecificFuelConsumption left, double right) { - return new BrakeSpecificFuelConsumption(left._kilogramsPerJoule*(double)right); + return new BrakeSpecificFuelConsumption(left.Value * right, left.Unit); } public static BrakeSpecificFuelConsumption operator /(BrakeSpecificFuelConsumption left, double right) { - return new BrakeSpecificFuelConsumption(left._kilogramsPerJoule/(double)right); + return new BrakeSpecificFuelConsumption(left.Value / right, left.Unit); } public static double operator /(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return Convert.ToDouble(left._kilogramsPerJoule/right._kilogramsPerJoule); + return left.KilogramsPerJoule / right.KilogramsPerJoule; } #endif @@ -406,43 +409,43 @@ public int CompareTo(object obj) #endif int CompareTo(BrakeSpecificFuelConsumption other) { - return _kilogramsPerJoule.CompareTo(other._kilogramsPerJoule); + return AsBaseUnitKilogramsPerJoule().CompareTo(other.AsBaseUnitKilogramsPerJoule()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return left._kilogramsPerJoule <= right._kilogramsPerJoule; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return left._kilogramsPerJoule >= right._kilogramsPerJoule; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return left._kilogramsPerJoule < right._kilogramsPerJoule; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return left._kilogramsPerJoule > right._kilogramsPerJoule; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerJoule == right._kilogramsPerJoule; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerJoule != right._kilogramsPerJoule; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -454,7 +457,7 @@ public override bool Equals(object obj) return false; } - return _kilogramsPerJoule.Equals(((BrakeSpecificFuelConsumption) obj)._kilogramsPerJoule); + return AsBaseUnitKilogramsPerJoule().Equals(((BrakeSpecificFuelConsumption) obj).AsBaseUnitKilogramsPerJoule()); } /// @@ -467,12 +470,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(BrakeSpecificFuelConsumption other, BrakeSpecificFuelConsumption maxError) { - return Math.Abs(_kilogramsPerJoule - other._kilogramsPerJoule) <= maxError._kilogramsPerJoule; + return Math.Abs(AsBaseUnitKilogramsPerJoule() - other.AsBaseUnitKilogramsPerJoule()) <= maxError.AsBaseUnitKilogramsPerJoule(); } public override int GetHashCode() { - return _kilogramsPerJoule.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -482,18 +485,21 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(BrakeSpecificFuelConsumptionUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitKilogramsPerJoule(); + switch (unit) { - case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: - return GramsPerKiloWattHour; - case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: - return KilogramsPerJoule; - case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: - return PoundsPerMechanicalHorsepowerHour; + case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: return baseUnitValue*3.6e9; + case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: return baseUnitValue; + case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: return baseUnitValue/1.689659410672e-7; default: throw new NotImplementedException("unit: " + unit); @@ -535,7 +541,11 @@ public static BrakeSpecificFuelConsumption Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -554,17 +564,24 @@ public static BrakeSpecificFuelConsumption Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static BrakeSpecificFuelConsumption Parse(string str, [CanBeNull] Culture culture) + public static BrakeSpecificFuelConsumption Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -590,16 +607,41 @@ public static bool TryParse([CanBeNull] string str, out BrakeSpecificFuelConsump /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out BrakeSpecificFuelConsumption result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out BrakeSpecificFuelConsumption result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -612,6 +654,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -625,11 +668,14 @@ public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -638,6 +684,8 @@ public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, [CanBeNull] /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -650,18 +698,18 @@ public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, [CanBeNull] #else public #endif - static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == BrakeSpecificFuelConsumptionUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized BrakeSpecificFuelConsumptionUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -670,6 +718,7 @@ static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider fo #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is KilogramPerJoule /// @@ -681,7 +730,7 @@ static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider fo /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -698,74 +747,131 @@ public string ToString(BrakeSpecificFuelConsumptionUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] Culture culture) + public string ToString( + BrakeSpecificFuelConsumptionUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + BrakeSpecificFuelConsumptionUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(BrakeSpecificFuelConsumptionUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + BrakeSpecificFuelConsumptionUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of BrakeSpecificFuelConsumption /// - public static BrakeSpecificFuelConsumption MaxValue - { - get - { - return new BrakeSpecificFuelConsumption(double.MaxValue); - } - } + public static BrakeSpecificFuelConsumption MaxValue => new BrakeSpecificFuelConsumption(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of BrakeSpecificFuelConsumption /// - public static BrakeSpecificFuelConsumption MinValue + public static BrakeSpecificFuelConsumption MinValue => new BrakeSpecificFuelConsumption(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitKilogramsPerJoule() { - get + if (Unit == BrakeSpecificFuelConsumptionUnit.KilogramPerJoule) { return _value; } + + switch (Unit) { - return new BrakeSpecificFuelConsumption(double.MinValue); - } - } - } + case BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour: return _value/3.6e9; + case BrakeSpecificFuelConsumptionUnit.KilogramPerJoule: return _value; + case BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour: return _value*1.689659410672e-7; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(BrakeSpecificFuelConsumptionUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs b/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs index f869fd208d..fe618621a5 100644 --- a/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Capacitance.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Capacitance : IComparable, IComparable #endif { /// - /// Base unit of Capacitance. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly CapacitanceUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _farads; + public CapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Capacitance() : this(0) + public Capacitance() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Capacitance(double farads) { - _farads = Convert.ToDouble(farads); + _value = Convert.ToDouble(farads); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Capacitance(double numericValue, CapacitanceUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Farad. + /// + /// Value assuming base unit Farad. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Capacitance(long farads) - { - _farads = Convert.ToDouble(farads); - } + Capacitance(long farads) : this(Convert.ToDouble(farads), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Farad. + /// + /// Value assuming base unit Farad. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Capacitance(decimal farads) - { - _farads = Convert.ToDouble(farads); - } + Capacitance(decimal farads) : this(Convert.ToDouble(farads), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public Capacitance(double farads) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static CapacitanceUnit BaseUnit - { - get { return CapacitanceUnit.Farad; } - } + public static CapacitanceUnit BaseUnit => CapacitanceUnit.Farad; /// /// All units of measurement for the Capacitance quantity. /// public static CapacitanceUnit[] Units { get; } = Enum.GetValues(typeof(CapacitanceUnit)).Cast().ToArray(); - /// /// Get Capacitance in Farads. /// - public double Farads - { - get { return _farads; } - } + public double Farads => As(CapacitanceUnit.Farad); #endregion #region Static - public static Capacitance Zero - { - get { return new Capacitance(); } - } + public static Capacitance Zero => new Capacitance(0, BaseUnit); /// /// Get Capacitance from Farads. @@ -152,17 +179,13 @@ public static Capacitance Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Capacitance FromFarads(double farads) - { - double value = (double) farads; - return new Capacitance(value); - } #else public static Capacitance FromFarads(QuantityValue farads) +#endif { double value = (double) farads; - return new Capacitance((value)); + return new Capacitance(value, CapacitanceUnit.Farad); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static Capacitance From(double value, CapacitanceUnit fromUnit) public static Capacitance From(QuantityValue value, CapacitanceUnit fromUnit) #endif { - switch (fromUnit) - { - case CapacitanceUnit.Farad: - return FromFarads(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Capacitance((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static Capacitance From(QuantityValue value, CapacitanceUnit fromUnit) { return null; } - switch (fromUnit) - { - case CapacitanceUnit.Farad: - return FromFarads(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Capacitance((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(CapacitanceUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(CapacitanceUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + CapacitanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(CapacitanceUnit unit, [CanBeNull] Culture c #if !WINDOWS_UWP public static Capacitance operator -(Capacitance right) { - return new Capacitance(-right._farads); + return new Capacitance(-right.Value, right.Unit); } public static Capacitance operator +(Capacitance left, Capacitance right) { - return new Capacitance(left._farads + right._farads); + return new Capacitance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Capacitance operator -(Capacitance left, Capacitance right) { - return new Capacitance(left._farads - right._farads); + return new Capacitance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Capacitance operator *(double left, Capacitance right) { - return new Capacitance(left*right._farads); + return new Capacitance(left * right.Value, right.Unit); } public static Capacitance operator *(Capacitance left, double right) { - return new Capacitance(left._farads*(double)right); + return new Capacitance(left.Value * right, left.Unit); } public static Capacitance operator /(Capacitance left, double right) { - return new Capacitance(left._farads/(double)right); + return new Capacitance(left.Value / right, left.Unit); } public static double operator /(Capacitance left, Capacitance right) { - return Convert.ToDouble(left._farads/right._farads); + return left.Farads / right.Farads; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(Capacitance other) { - return _farads.CompareTo(other._farads); + return AsBaseUnitFarads().CompareTo(other.AsBaseUnitFarads()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Capacitance left, Capacitance right) { - return left._farads <= right._farads; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Capacitance left, Capacitance right) { - return left._farads >= right._farads; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Capacitance left, Capacitance right) { - return left._farads < right._farads; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Capacitance left, Capacitance right) { - return left._farads > right._farads; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Capacitance left, Capacitance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._farads == right._farads; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Capacitance left, Capacitance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._farads != right._farads; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _farads.Equals(((Capacitance) obj)._farads); + return AsBaseUnitFarads().Equals(((Capacitance) obj).AsBaseUnitFarads()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Capacitance other, Capacitance maxError) { - return Math.Abs(_farads - other._farads) <= maxError._farads; + return Math.Abs(AsBaseUnitFarads() - other.AsBaseUnitFarads()) <= maxError.AsBaseUnitFarads(); } public override int GetHashCode() { - return _farads.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(CapacitanceUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitFarads(); + switch (unit) { - case CapacitanceUnit.Farad: - return Farads; + case CapacitanceUnit.Farad: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static Capacitance Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static Capacitance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Capacitance Parse(string str, [CanBeNull] Culture culture) + public static Capacitance Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out Capacitance result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Capacitance result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Capacitance result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static CapacitanceUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static CapacitanceUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static CapacitanceUnit ParseUnit(string str, [CanBeNull] string cultureNa /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static CapacitanceUnit ParseUnit(string str, [CanBeNull] string cultureNa #else public #endif - static CapacitanceUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static CapacitanceUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == CapacitanceUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized CapacitanceUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static CapacitanceUnit ParseUnit(string str, IFormatProvider formatProvider = nu #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Farad /// @@ -587,7 +662,7 @@ static CapacitanceUnit ParseUnit(string str, IFormatProvider formatProvider = nu /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(CapacitanceUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(CapacitanceUnit unit, [CanBeNull] Culture culture) + public string ToString( + CapacitanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(CapacitanceUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + CapacitanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(CapacitanceUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + CapacitanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Capacitance /// - public static Capacitance MaxValue - { - get - { - return new Capacitance(double.MaxValue); - } - } + public static Capacitance MaxValue => new Capacitance(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Capacitance /// - public static Capacitance MinValue + public static Capacitance MinValue => new Capacitance(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitFarads() { - get + if (Unit == CapacitanceUnit.Farad) { return _value; } + + switch (Unit) { - return new Capacitance(double.MinValue); - } - } - } + case CapacitanceUnit.Farad: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(CapacitanceUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Density.g.cs b/UnitsNet/GeneratedCode/Quantities/Density.g.cs index 82c76f7d49..b0428f76e1 100644 --- a/UnitsNet/GeneratedCode/Quantities/Density.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Density.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Density : IComparable, IComparable #endif { /// - /// Base unit of Density. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _kilogramsPerCubicMeter; + private readonly DensityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Density() : this(0) + public Density() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Density(double kilogramspercubicmeter) { - _kilogramsPerCubicMeter = Convert.ToDouble(kilogramspercubicmeter); + _value = Convert.ToDouble(kilogramspercubicmeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Density(double numericValue, DensityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerCubicMeter. + /// + /// Value assuming base unit KilogramPerCubicMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Density(long kilogramspercubicmeter) - { - _kilogramsPerCubicMeter = Convert.ToDouble(kilogramspercubicmeter); - } + Density(long kilogramspercubicmeter) : this(Convert.ToDouble(kilogramspercubicmeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerCubicMeter. + /// + /// Value assuming base unit KilogramPerCubicMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Density(decimal kilogramspercubicmeter) - { - _kilogramsPerCubicMeter = Convert.ToDouble(kilogramspercubicmeter); - } + Density(decimal kilogramspercubicmeter) : this(Convert.ToDouble(kilogramspercubicmeter), BaseUnit) { } #region Properties @@ -119,328 +156,170 @@ public Density(double kilogramspercubicmeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static DensityUnit BaseUnit - { - get { return DensityUnit.KilogramPerCubicMeter; } - } + public static DensityUnit BaseUnit => DensityUnit.KilogramPerCubicMeter; /// /// All units of measurement for the Density quantity. /// public static DensityUnit[] Units { get; } = Enum.GetValues(typeof(DensityUnit)).Cast().ToArray(); - /// /// Get Density in CentigramsPerDeciLiter. /// - public double CentigramsPerDeciLiter - { - get { return (_kilogramsPerCubicMeter*1e-1) / 1e-2d; } - } - + public double CentigramsPerDeciLiter => As(DensityUnit.CentigramPerDeciliter); /// /// Get Density in CentigramsPerLiter. /// - public double CentigramsPerLiter - { - get { return (_kilogramsPerCubicMeter*1) / 1e-2d; } - } - + public double CentigramsPerLiter => As(DensityUnit.CentigramPerLiter); /// /// Get Density in CentigramsPerMilliliter. /// - public double CentigramsPerMilliliter - { - get { return (_kilogramsPerCubicMeter*1e-3) / 1e-2d; } - } - + public double CentigramsPerMilliliter => As(DensityUnit.CentigramPerMilliliter); /// /// Get Density in DecigramsPerDeciLiter. /// - public double DecigramsPerDeciLiter - { - get { return (_kilogramsPerCubicMeter*1e-1) / 1e-1d; } - } - + public double DecigramsPerDeciLiter => As(DensityUnit.DecigramPerDeciliter); /// /// Get Density in DecigramsPerLiter. /// - public double DecigramsPerLiter - { - get { return (_kilogramsPerCubicMeter*1) / 1e-1d; } - } - + public double DecigramsPerLiter => As(DensityUnit.DecigramPerLiter); /// /// Get Density in DecigramsPerMilliliter. /// - public double DecigramsPerMilliliter - { - get { return (_kilogramsPerCubicMeter*1e-3) / 1e-1d; } - } - + public double DecigramsPerMilliliter => As(DensityUnit.DecigramPerMilliliter); /// /// Get Density in GramsPerCubicCentimeter. /// - public double GramsPerCubicCentimeter - { - get { return _kilogramsPerCubicMeter*1e-3; } - } - + public double GramsPerCubicCentimeter => As(DensityUnit.GramPerCubicCentimeter); /// /// Get Density in GramsPerCubicMeter. /// - public double GramsPerCubicMeter - { - get { return _kilogramsPerCubicMeter*1e3; } - } - + public double GramsPerCubicMeter => As(DensityUnit.GramPerCubicMeter); /// /// Get Density in GramsPerCubicMillimeter. /// - public double GramsPerCubicMillimeter - { - get { return _kilogramsPerCubicMeter*1e-6; } - } - + public double GramsPerCubicMillimeter => As(DensityUnit.GramPerCubicMillimeter); /// /// Get Density in GramsPerDeciLiter. /// - public double GramsPerDeciLiter - { - get { return _kilogramsPerCubicMeter*1e-1; } - } - + public double GramsPerDeciLiter => As(DensityUnit.GramPerDeciliter); /// /// Get Density in GramsPerLiter. /// - public double GramsPerLiter - { - get { return _kilogramsPerCubicMeter*1; } - } - + public double GramsPerLiter => As(DensityUnit.GramPerLiter); /// /// Get Density in GramsPerMilliliter. /// - public double GramsPerMilliliter - { - get { return _kilogramsPerCubicMeter*1e-3; } - } - + public double GramsPerMilliliter => As(DensityUnit.GramPerMilliliter); /// /// Get Density in KilogramsPerCubicCentimeter. /// - public double KilogramsPerCubicCentimeter - { - get { return (_kilogramsPerCubicMeter*1e-3) / 1e3d; } - } - + public double KilogramsPerCubicCentimeter => As(DensityUnit.KilogramPerCubicCentimeter); /// /// Get Density in KilogramsPerCubicMeter. /// - public double KilogramsPerCubicMeter - { - get { return (_kilogramsPerCubicMeter*1e3) / 1e3d; } - } - + public double KilogramsPerCubicMeter => As(DensityUnit.KilogramPerCubicMeter); /// /// Get Density in KilogramsPerCubicMillimeter. /// - public double KilogramsPerCubicMillimeter - { - get { return (_kilogramsPerCubicMeter*1e-6) / 1e3d; } - } - + public double KilogramsPerCubicMillimeter => As(DensityUnit.KilogramPerCubicMillimeter); /// /// Get Density in KilopoundsPerCubicFoot. /// - public double KilopoundsPerCubicFoot - { - get { return (_kilogramsPerCubicMeter*0.062427961) / 1e3d; } - } - + public double KilopoundsPerCubicFoot => As(DensityUnit.KilopoundPerCubicFoot); /// /// Get Density in KilopoundsPerCubicInch. /// - public double KilopoundsPerCubicInch - { - get { return (_kilogramsPerCubicMeter*3.6127298147753e-5) / 1e3d; } - } - + public double KilopoundsPerCubicInch => As(DensityUnit.KilopoundPerCubicInch); /// /// Get Density in MicrogramsPerDeciLiter. /// - public double MicrogramsPerDeciLiter - { - get { return (_kilogramsPerCubicMeter*1e-1) / 1e-6d; } - } - + public double MicrogramsPerDeciLiter => As(DensityUnit.MicrogramPerDeciliter); /// /// Get Density in MicrogramsPerLiter. /// - public double MicrogramsPerLiter - { - get { return (_kilogramsPerCubicMeter*1) / 1e-6d; } - } - + public double MicrogramsPerLiter => As(DensityUnit.MicrogramPerLiter); /// /// Get Density in MicrogramsPerMilliliter. /// - public double MicrogramsPerMilliliter - { - get { return (_kilogramsPerCubicMeter*1e-3) / 1e-6d; } - } - + public double MicrogramsPerMilliliter => As(DensityUnit.MicrogramPerMilliliter); /// /// Get Density in MilligramsPerCubicMeter. /// - public double MilligramsPerCubicMeter - { - get { return (_kilogramsPerCubicMeter*1e3) / 1e-3d; } - } - + public double MilligramsPerCubicMeter => As(DensityUnit.MilligramPerCubicMeter); /// /// Get Density in MilligramsPerDeciLiter. /// - public double MilligramsPerDeciLiter - { - get { return (_kilogramsPerCubicMeter*1e-1) / 1e-3d; } - } - + public double MilligramsPerDeciLiter => As(DensityUnit.MilligramPerDeciliter); /// /// Get Density in MilligramsPerLiter. /// - public double MilligramsPerLiter - { - get { return (_kilogramsPerCubicMeter*1) / 1e-3d; } - } - + public double MilligramsPerLiter => As(DensityUnit.MilligramPerLiter); /// /// Get Density in MilligramsPerMilliliter. /// - public double MilligramsPerMilliliter - { - get { return (_kilogramsPerCubicMeter*1e-3) / 1e-3d; } - } - + public double MilligramsPerMilliliter => As(DensityUnit.MilligramPerMilliliter); /// /// Get Density in NanogramsPerDeciLiter. /// - public double NanogramsPerDeciLiter - { - get { return (_kilogramsPerCubicMeter*1e-1) / 1e-9d; } - } - + public double NanogramsPerDeciLiter => As(DensityUnit.NanogramPerDeciliter); /// /// Get Density in NanogramsPerLiter. /// - public double NanogramsPerLiter - { - get { return (_kilogramsPerCubicMeter*1) / 1e-9d; } - } - + public double NanogramsPerLiter => As(DensityUnit.NanogramPerLiter); /// /// Get Density in NanogramsPerMilliliter. /// - public double NanogramsPerMilliliter - { - get { return (_kilogramsPerCubicMeter*1e-3) / 1e-9d; } - } - + public double NanogramsPerMilliliter => As(DensityUnit.NanogramPerMilliliter); /// /// Get Density in PicogramsPerDeciLiter. /// - public double PicogramsPerDeciLiter - { - get { return (_kilogramsPerCubicMeter*1e-1) / 1e-12d; } - } - + public double PicogramsPerDeciLiter => As(DensityUnit.PicogramPerDeciliter); /// /// Get Density in PicogramsPerLiter. /// - public double PicogramsPerLiter - { - get { return (_kilogramsPerCubicMeter*1) / 1e-12d; } - } - + public double PicogramsPerLiter => As(DensityUnit.PicogramPerLiter); /// /// Get Density in PicogramsPerMilliliter. /// - public double PicogramsPerMilliliter - { - get { return (_kilogramsPerCubicMeter*1e-3) / 1e-12d; } - } - + public double PicogramsPerMilliliter => As(DensityUnit.PicogramPerMilliliter); /// /// Get Density in PoundsPerCubicFoot. /// - public double PoundsPerCubicFoot - { - get { return _kilogramsPerCubicMeter*0.062427961; } - } - + public double PoundsPerCubicFoot => As(DensityUnit.PoundPerCubicFoot); /// /// Get Density in PoundsPerCubicInch. /// - public double PoundsPerCubicInch - { - get { return _kilogramsPerCubicMeter*3.6127298147753e-5; } - } - + public double PoundsPerCubicInch => As(DensityUnit.PoundPerCubicInch); /// /// Get Density in PoundsPerImperialGallon. /// - public double PoundsPerImperialGallon - { - get { return _kilogramsPerCubicMeter/9.9776398e1; } - } - + public double PoundsPerImperialGallon => As(DensityUnit.PoundPerImperialGallon); /// /// Get Density in PoundsPerUSGallon. /// - public double PoundsPerUSGallon - { - get { return _kilogramsPerCubicMeter/1.19826427e2; } - } - + public double PoundsPerUSGallon => As(DensityUnit.PoundPerUSGallon); /// /// Get Density in SlugsPerCubicFoot. /// - public double SlugsPerCubicFoot - { - get { return _kilogramsPerCubicMeter*0.00194032033; } - } - + public double SlugsPerCubicFoot => As(DensityUnit.SlugPerCubicFoot); /// /// Get Density in TonnesPerCubicCentimeter. /// - public double TonnesPerCubicCentimeter - { - get { return _kilogramsPerCubicMeter*1e-9; } - } - + public double TonnesPerCubicCentimeter => As(DensityUnit.TonnePerCubicCentimeter); /// /// Get Density in TonnesPerCubicMeter. /// - public double TonnesPerCubicMeter - { - get { return _kilogramsPerCubicMeter*0.001; } - } - + public double TonnesPerCubicMeter => As(DensityUnit.TonnePerCubicMeter); /// /// Get Density in TonnesPerCubicMillimeter. /// - public double TonnesPerCubicMillimeter - { - get { return _kilogramsPerCubicMeter*1e-12; } - } + public double TonnesPerCubicMillimeter => As(DensityUnit.TonnePerCubicMillimeter); #endregion #region Static - public static Density Zero - { - get { return new Density(); } - } + public static Density Zero => new Density(0, BaseUnit); /// /// Get Density from CentigramsPerDeciLiter. @@ -448,17 +327,13 @@ public static Density Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromCentigramsPerDeciLiter(double centigramsperdeciliter) - { - double value = (double) centigramsperdeciliter; - return new Density((value/1e-1) * 1e-2d); - } #else public static Density FromCentigramsPerDeciLiter(QuantityValue centigramsperdeciliter) +#endif { double value = (double) centigramsperdeciliter; - return new Density(((value/1e-1) * 1e-2d)); + return new Density(value, DensityUnit.CentigramPerDeciliter); } -#endif /// /// Get Density from CentigramsPerLiter. @@ -466,17 +341,13 @@ public static Density FromCentigramsPerDeciLiter(QuantityValue centigramsperdeci #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromCentigramsPerLiter(double centigramsperliter) - { - double value = (double) centigramsperliter; - return new Density((value/1) * 1e-2d); - } #else public static Density FromCentigramsPerLiter(QuantityValue centigramsperliter) +#endif { double value = (double) centigramsperliter; - return new Density(((value/1) * 1e-2d)); + return new Density(value, DensityUnit.CentigramPerLiter); } -#endif /// /// Get Density from CentigramsPerMilliliter. @@ -484,17 +355,13 @@ public static Density FromCentigramsPerLiter(QuantityValue centigramsperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromCentigramsPerMilliliter(double centigramspermilliliter) - { - double value = (double) centigramspermilliliter; - return new Density((value/1e-3) * 1e-2d); - } #else public static Density FromCentigramsPerMilliliter(QuantityValue centigramspermilliliter) +#endif { double value = (double) centigramspermilliliter; - return new Density(((value/1e-3) * 1e-2d)); + return new Density(value, DensityUnit.CentigramPerMilliliter); } -#endif /// /// Get Density from DecigramsPerDeciLiter. @@ -502,17 +369,13 @@ public static Density FromCentigramsPerMilliliter(QuantityValue centigramspermil #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromDecigramsPerDeciLiter(double decigramsperdeciliter) - { - double value = (double) decigramsperdeciliter; - return new Density((value/1e-1) * 1e-1d); - } #else public static Density FromDecigramsPerDeciLiter(QuantityValue decigramsperdeciliter) +#endif { double value = (double) decigramsperdeciliter; - return new Density(((value/1e-1) * 1e-1d)); + return new Density(value, DensityUnit.DecigramPerDeciliter); } -#endif /// /// Get Density from DecigramsPerLiter. @@ -520,17 +383,13 @@ public static Density FromDecigramsPerDeciLiter(QuantityValue decigramsperdecili #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromDecigramsPerLiter(double decigramsperliter) - { - double value = (double) decigramsperliter; - return new Density((value/1) * 1e-1d); - } #else public static Density FromDecigramsPerLiter(QuantityValue decigramsperliter) +#endif { double value = (double) decigramsperliter; - return new Density(((value/1) * 1e-1d)); + return new Density(value, DensityUnit.DecigramPerLiter); } -#endif /// /// Get Density from DecigramsPerMilliliter. @@ -538,17 +397,13 @@ public static Density FromDecigramsPerLiter(QuantityValue decigramsperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromDecigramsPerMilliliter(double decigramspermilliliter) - { - double value = (double) decigramspermilliliter; - return new Density((value/1e-3) * 1e-1d); - } #else public static Density FromDecigramsPerMilliliter(QuantityValue decigramspermilliliter) +#endif { double value = (double) decigramspermilliliter; - return new Density(((value/1e-3) * 1e-1d)); + return new Density(value, DensityUnit.DecigramPerMilliliter); } -#endif /// /// Get Density from GramsPerCubicCentimeter. @@ -556,17 +411,13 @@ public static Density FromDecigramsPerMilliliter(QuantityValue decigramspermilli #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromGramsPerCubicCentimeter(double gramspercubiccentimeter) - { - double value = (double) gramspercubiccentimeter; - return new Density(value/1e-3); - } #else public static Density FromGramsPerCubicCentimeter(QuantityValue gramspercubiccentimeter) +#endif { double value = (double) gramspercubiccentimeter; - return new Density((value/1e-3)); + return new Density(value, DensityUnit.GramPerCubicCentimeter); } -#endif /// /// Get Density from GramsPerCubicMeter. @@ -574,17 +425,13 @@ public static Density FromGramsPerCubicCentimeter(QuantityValue gramspercubiccen #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromGramsPerCubicMeter(double gramspercubicmeter) - { - double value = (double) gramspercubicmeter; - return new Density(value/1e3); - } #else public static Density FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) +#endif { double value = (double) gramspercubicmeter; - return new Density((value/1e3)); + return new Density(value, DensityUnit.GramPerCubicMeter); } -#endif /// /// Get Density from GramsPerCubicMillimeter. @@ -592,17 +439,13 @@ public static Density FromGramsPerCubicMeter(QuantityValue gramspercubicmeter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromGramsPerCubicMillimeter(double gramspercubicmillimeter) - { - double value = (double) gramspercubicmillimeter; - return new Density(value/1e-6); - } #else public static Density FromGramsPerCubicMillimeter(QuantityValue gramspercubicmillimeter) +#endif { double value = (double) gramspercubicmillimeter; - return new Density((value/1e-6)); + return new Density(value, DensityUnit.GramPerCubicMillimeter); } -#endif /// /// Get Density from GramsPerDeciLiter. @@ -610,17 +453,13 @@ public static Density FromGramsPerCubicMillimeter(QuantityValue gramspercubicmil #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromGramsPerDeciLiter(double gramsperdeciliter) - { - double value = (double) gramsperdeciliter; - return new Density(value/1e-1); - } #else public static Density FromGramsPerDeciLiter(QuantityValue gramsperdeciliter) +#endif { double value = (double) gramsperdeciliter; - return new Density((value/1e-1)); + return new Density(value, DensityUnit.GramPerDeciliter); } -#endif /// /// Get Density from GramsPerLiter. @@ -628,17 +467,13 @@ public static Density FromGramsPerDeciLiter(QuantityValue gramsperdeciliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromGramsPerLiter(double gramsperliter) - { - double value = (double) gramsperliter; - return new Density(value/1); - } #else public static Density FromGramsPerLiter(QuantityValue gramsperliter) +#endif { double value = (double) gramsperliter; - return new Density((value/1)); + return new Density(value, DensityUnit.GramPerLiter); } -#endif /// /// Get Density from GramsPerMilliliter. @@ -646,17 +481,13 @@ public static Density FromGramsPerLiter(QuantityValue gramsperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromGramsPerMilliliter(double gramspermilliliter) - { - double value = (double) gramspermilliliter; - return new Density(value/1e-3); - } #else public static Density FromGramsPerMilliliter(QuantityValue gramspermilliliter) +#endif { double value = (double) gramspermilliliter; - return new Density((value/1e-3)); + return new Density(value, DensityUnit.GramPerMilliliter); } -#endif /// /// Get Density from KilogramsPerCubicCentimeter. @@ -664,17 +495,13 @@ public static Density FromGramsPerMilliliter(QuantityValue gramspermilliliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromKilogramsPerCubicCentimeter(double kilogramspercubiccentimeter) - { - double value = (double) kilogramspercubiccentimeter; - return new Density((value/1e-3) * 1e3d); - } #else public static Density FromKilogramsPerCubicCentimeter(QuantityValue kilogramspercubiccentimeter) +#endif { double value = (double) kilogramspercubiccentimeter; - return new Density(((value/1e-3) * 1e3d)); + return new Density(value, DensityUnit.KilogramPerCubicCentimeter); } -#endif /// /// Get Density from KilogramsPerCubicMeter. @@ -682,17 +509,13 @@ public static Density FromKilogramsPerCubicCentimeter(QuantityValue kilogramsper #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromKilogramsPerCubicMeter(double kilogramspercubicmeter) - { - double value = (double) kilogramspercubicmeter; - return new Density((value/1e3) * 1e3d); - } #else public static Density FromKilogramsPerCubicMeter(QuantityValue kilogramspercubicmeter) +#endif { double value = (double) kilogramspercubicmeter; - return new Density(((value/1e3) * 1e3d)); + return new Density(value, DensityUnit.KilogramPerCubicMeter); } -#endif /// /// Get Density from KilogramsPerCubicMillimeter. @@ -700,17 +523,13 @@ public static Density FromKilogramsPerCubicMeter(QuantityValue kilogramspercubic #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromKilogramsPerCubicMillimeter(double kilogramspercubicmillimeter) - { - double value = (double) kilogramspercubicmillimeter; - return new Density((value/1e-6) * 1e3d); - } #else public static Density FromKilogramsPerCubicMillimeter(QuantityValue kilogramspercubicmillimeter) +#endif { double value = (double) kilogramspercubicmillimeter; - return new Density(((value/1e-6) * 1e3d)); + return new Density(value, DensityUnit.KilogramPerCubicMillimeter); } -#endif /// /// Get Density from KilopoundsPerCubicFoot. @@ -718,17 +537,13 @@ public static Density FromKilogramsPerCubicMillimeter(QuantityValue kilogramsper #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromKilopoundsPerCubicFoot(double kilopoundspercubicfoot) - { - double value = (double) kilopoundspercubicfoot; - return new Density((value/0.062427961) * 1e3d); - } #else public static Density FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubicfoot) +#endif { double value = (double) kilopoundspercubicfoot; - return new Density(((value/0.062427961) * 1e3d)); + return new Density(value, DensityUnit.KilopoundPerCubicFoot); } -#endif /// /// Get Density from KilopoundsPerCubicInch. @@ -736,17 +551,13 @@ public static Density FromKilopoundsPerCubicFoot(QuantityValue kilopoundspercubi #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromKilopoundsPerCubicInch(double kilopoundspercubicinch) - { - double value = (double) kilopoundspercubicinch; - return new Density((value/3.6127298147753e-5) * 1e3d); - } #else public static Density FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubicinch) +#endif { double value = (double) kilopoundspercubicinch; - return new Density(((value/3.6127298147753e-5) * 1e3d)); + return new Density(value, DensityUnit.KilopoundPerCubicInch); } -#endif /// /// Get Density from MicrogramsPerDeciLiter. @@ -754,17 +565,13 @@ public static Density FromKilopoundsPerCubicInch(QuantityValue kilopoundspercubi #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromMicrogramsPerDeciLiter(double microgramsperdeciliter) - { - double value = (double) microgramsperdeciliter; - return new Density((value/1e-1) * 1e-6d); - } #else public static Density FromMicrogramsPerDeciLiter(QuantityValue microgramsperdeciliter) +#endif { double value = (double) microgramsperdeciliter; - return new Density(((value/1e-1) * 1e-6d)); + return new Density(value, DensityUnit.MicrogramPerDeciliter); } -#endif /// /// Get Density from MicrogramsPerLiter. @@ -772,17 +579,13 @@ public static Density FromMicrogramsPerDeciLiter(QuantityValue microgramsperdeci #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromMicrogramsPerLiter(double microgramsperliter) - { - double value = (double) microgramsperliter; - return new Density((value/1) * 1e-6d); - } #else public static Density FromMicrogramsPerLiter(QuantityValue microgramsperliter) +#endif { double value = (double) microgramsperliter; - return new Density(((value/1) * 1e-6d)); + return new Density(value, DensityUnit.MicrogramPerLiter); } -#endif /// /// Get Density from MicrogramsPerMilliliter. @@ -790,17 +593,13 @@ public static Density FromMicrogramsPerLiter(QuantityValue microgramsperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromMicrogramsPerMilliliter(double microgramspermilliliter) - { - double value = (double) microgramspermilliliter; - return new Density((value/1e-3) * 1e-6d); - } #else public static Density FromMicrogramsPerMilliliter(QuantityValue microgramspermilliliter) +#endif { double value = (double) microgramspermilliliter; - return new Density(((value/1e-3) * 1e-6d)); + return new Density(value, DensityUnit.MicrogramPerMilliliter); } -#endif /// /// Get Density from MilligramsPerCubicMeter. @@ -808,17 +607,13 @@ public static Density FromMicrogramsPerMilliliter(QuantityValue microgramspermil #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromMilligramsPerCubicMeter(double milligramspercubicmeter) - { - double value = (double) milligramspercubicmeter; - return new Density((value/1e3) * 1e-3d); - } #else public static Density FromMilligramsPerCubicMeter(QuantityValue milligramspercubicmeter) +#endif { double value = (double) milligramspercubicmeter; - return new Density(((value/1e3) * 1e-3d)); + return new Density(value, DensityUnit.MilligramPerCubicMeter); } -#endif /// /// Get Density from MilligramsPerDeciLiter. @@ -826,17 +621,13 @@ public static Density FromMilligramsPerCubicMeter(QuantityValue milligramspercub #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromMilligramsPerDeciLiter(double milligramsperdeciliter) - { - double value = (double) milligramsperdeciliter; - return new Density((value/1e-1) * 1e-3d); - } #else public static Density FromMilligramsPerDeciLiter(QuantityValue milligramsperdeciliter) +#endif { double value = (double) milligramsperdeciliter; - return new Density(((value/1e-1) * 1e-3d)); + return new Density(value, DensityUnit.MilligramPerDeciliter); } -#endif /// /// Get Density from MilligramsPerLiter. @@ -844,17 +635,13 @@ public static Density FromMilligramsPerDeciLiter(QuantityValue milligramsperdeci #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromMilligramsPerLiter(double milligramsperliter) - { - double value = (double) milligramsperliter; - return new Density((value/1) * 1e-3d); - } #else public static Density FromMilligramsPerLiter(QuantityValue milligramsperliter) +#endif { double value = (double) milligramsperliter; - return new Density(((value/1) * 1e-3d)); + return new Density(value, DensityUnit.MilligramPerLiter); } -#endif /// /// Get Density from MilligramsPerMilliliter. @@ -862,17 +649,13 @@ public static Density FromMilligramsPerLiter(QuantityValue milligramsperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromMilligramsPerMilliliter(double milligramspermilliliter) - { - double value = (double) milligramspermilliliter; - return new Density((value/1e-3) * 1e-3d); - } #else public static Density FromMilligramsPerMilliliter(QuantityValue milligramspermilliliter) +#endif { double value = (double) milligramspermilliliter; - return new Density(((value/1e-3) * 1e-3d)); + return new Density(value, DensityUnit.MilligramPerMilliliter); } -#endif /// /// Get Density from NanogramsPerDeciLiter. @@ -880,17 +663,13 @@ public static Density FromMilligramsPerMilliliter(QuantityValue milligramspermil #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromNanogramsPerDeciLiter(double nanogramsperdeciliter) - { - double value = (double) nanogramsperdeciliter; - return new Density((value/1e-1) * 1e-9d); - } #else public static Density FromNanogramsPerDeciLiter(QuantityValue nanogramsperdeciliter) +#endif { double value = (double) nanogramsperdeciliter; - return new Density(((value/1e-1) * 1e-9d)); + return new Density(value, DensityUnit.NanogramPerDeciliter); } -#endif /// /// Get Density from NanogramsPerLiter. @@ -898,17 +677,13 @@ public static Density FromNanogramsPerDeciLiter(QuantityValue nanogramsperdecili #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromNanogramsPerLiter(double nanogramsperliter) - { - double value = (double) nanogramsperliter; - return new Density((value/1) * 1e-9d); - } #else public static Density FromNanogramsPerLiter(QuantityValue nanogramsperliter) +#endif { double value = (double) nanogramsperliter; - return new Density(((value/1) * 1e-9d)); + return new Density(value, DensityUnit.NanogramPerLiter); } -#endif /// /// Get Density from NanogramsPerMilliliter. @@ -916,17 +691,13 @@ public static Density FromNanogramsPerLiter(QuantityValue nanogramsperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromNanogramsPerMilliliter(double nanogramspermilliliter) - { - double value = (double) nanogramspermilliliter; - return new Density((value/1e-3) * 1e-9d); - } #else public static Density FromNanogramsPerMilliliter(QuantityValue nanogramspermilliliter) +#endif { double value = (double) nanogramspermilliliter; - return new Density(((value/1e-3) * 1e-9d)); + return new Density(value, DensityUnit.NanogramPerMilliliter); } -#endif /// /// Get Density from PicogramsPerDeciLiter. @@ -934,17 +705,13 @@ public static Density FromNanogramsPerMilliliter(QuantityValue nanogramspermilli #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromPicogramsPerDeciLiter(double picogramsperdeciliter) - { - double value = (double) picogramsperdeciliter; - return new Density((value/1e-1) * 1e-12d); - } #else public static Density FromPicogramsPerDeciLiter(QuantityValue picogramsperdeciliter) +#endif { double value = (double) picogramsperdeciliter; - return new Density(((value/1e-1) * 1e-12d)); + return new Density(value, DensityUnit.PicogramPerDeciliter); } -#endif /// /// Get Density from PicogramsPerLiter. @@ -952,17 +719,13 @@ public static Density FromPicogramsPerDeciLiter(QuantityValue picogramsperdecili #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromPicogramsPerLiter(double picogramsperliter) - { - double value = (double) picogramsperliter; - return new Density((value/1) * 1e-12d); - } #else public static Density FromPicogramsPerLiter(QuantityValue picogramsperliter) +#endif { double value = (double) picogramsperliter; - return new Density(((value/1) * 1e-12d)); + return new Density(value, DensityUnit.PicogramPerLiter); } -#endif /// /// Get Density from PicogramsPerMilliliter. @@ -970,17 +733,13 @@ public static Density FromPicogramsPerLiter(QuantityValue picogramsperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromPicogramsPerMilliliter(double picogramspermilliliter) - { - double value = (double) picogramspermilliliter; - return new Density((value/1e-3) * 1e-12d); - } #else public static Density FromPicogramsPerMilliliter(QuantityValue picogramspermilliliter) +#endif { double value = (double) picogramspermilliliter; - return new Density(((value/1e-3) * 1e-12d)); + return new Density(value, DensityUnit.PicogramPerMilliliter); } -#endif /// /// Get Density from PoundsPerCubicFoot. @@ -988,17 +747,13 @@ public static Density FromPicogramsPerMilliliter(QuantityValue picogramspermilli #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromPoundsPerCubicFoot(double poundspercubicfoot) - { - double value = (double) poundspercubicfoot; - return new Density(value/0.062427961); - } #else public static Density FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) +#endif { double value = (double) poundspercubicfoot; - return new Density((value/0.062427961)); + return new Density(value, DensityUnit.PoundPerCubicFoot); } -#endif /// /// Get Density from PoundsPerCubicInch. @@ -1006,17 +761,13 @@ public static Density FromPoundsPerCubicFoot(QuantityValue poundspercubicfoot) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromPoundsPerCubicInch(double poundspercubicinch) - { - double value = (double) poundspercubicinch; - return new Density(value/3.6127298147753e-5); - } #else public static Density FromPoundsPerCubicInch(QuantityValue poundspercubicinch) +#endif { double value = (double) poundspercubicinch; - return new Density((value/3.6127298147753e-5)); + return new Density(value, DensityUnit.PoundPerCubicInch); } -#endif /// /// Get Density from PoundsPerImperialGallon. @@ -1024,17 +775,13 @@ public static Density FromPoundsPerCubicInch(QuantityValue poundspercubicinch) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromPoundsPerImperialGallon(double poundsperimperialgallon) - { - double value = (double) poundsperimperialgallon; - return new Density(value*9.9776398e1); - } #else public static Density FromPoundsPerImperialGallon(QuantityValue poundsperimperialgallon) +#endif { double value = (double) poundsperimperialgallon; - return new Density((value*9.9776398e1)); + return new Density(value, DensityUnit.PoundPerImperialGallon); } -#endif /// /// Get Density from PoundsPerUSGallon. @@ -1042,17 +789,13 @@ public static Density FromPoundsPerImperialGallon(QuantityValue poundsperimperia #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromPoundsPerUSGallon(double poundsperusgallon) - { - double value = (double) poundsperusgallon; - return new Density(value*1.19826427e2); - } #else public static Density FromPoundsPerUSGallon(QuantityValue poundsperusgallon) +#endif { double value = (double) poundsperusgallon; - return new Density((value*1.19826427e2)); + return new Density(value, DensityUnit.PoundPerUSGallon); } -#endif /// /// Get Density from SlugsPerCubicFoot. @@ -1060,17 +803,13 @@ public static Density FromPoundsPerUSGallon(QuantityValue poundsperusgallon) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromSlugsPerCubicFoot(double slugspercubicfoot) - { - double value = (double) slugspercubicfoot; - return new Density(value*515.378818); - } #else public static Density FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) +#endif { double value = (double) slugspercubicfoot; - return new Density((value*515.378818)); + return new Density(value, DensityUnit.SlugPerCubicFoot); } -#endif /// /// Get Density from TonnesPerCubicCentimeter. @@ -1078,17 +817,13 @@ public static Density FromSlugsPerCubicFoot(QuantityValue slugspercubicfoot) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromTonnesPerCubicCentimeter(double tonnespercubiccentimeter) - { - double value = (double) tonnespercubiccentimeter; - return new Density(value/1e-9); - } #else public static Density FromTonnesPerCubicCentimeter(QuantityValue tonnespercubiccentimeter) +#endif { double value = (double) tonnespercubiccentimeter; - return new Density((value/1e-9)); + return new Density(value, DensityUnit.TonnePerCubicCentimeter); } -#endif /// /// Get Density from TonnesPerCubicMeter. @@ -1096,17 +831,13 @@ public static Density FromTonnesPerCubicCentimeter(QuantityValue tonnespercubicc #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromTonnesPerCubicMeter(double tonnespercubicmeter) - { - double value = (double) tonnespercubicmeter; - return new Density(value/0.001); - } #else public static Density FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) +#endif { double value = (double) tonnespercubicmeter; - return new Density((value/0.001)); + return new Density(value, DensityUnit.TonnePerCubicMeter); } -#endif /// /// Get Density from TonnesPerCubicMillimeter. @@ -1114,17 +845,13 @@ public static Density FromTonnesPerCubicMeter(QuantityValue tonnespercubicmeter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Density FromTonnesPerCubicMillimeter(double tonnespercubicmillimeter) - { - double value = (double) tonnespercubicmillimeter; - return new Density(value/1e-12); - } #else public static Density FromTonnesPerCubicMillimeter(QuantityValue tonnespercubicmillimeter) +#endif { double value = (double) tonnespercubicmillimeter; - return new Density((value/1e-12)); + return new Density(value, DensityUnit.TonnePerCubicMillimeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1714,88 +1441,7 @@ public static Density From(double value, DensityUnit fromUnit) public static Density From(QuantityValue value, DensityUnit fromUnit) #endif { - switch (fromUnit) - { - case DensityUnit.CentigramPerDeciliter: - return FromCentigramsPerDeciLiter(value); - case DensityUnit.CentigramPerLiter: - return FromCentigramsPerLiter(value); - case DensityUnit.CentigramPerMilliliter: - return FromCentigramsPerMilliliter(value); - case DensityUnit.DecigramPerDeciliter: - return FromDecigramsPerDeciLiter(value); - case DensityUnit.DecigramPerLiter: - return FromDecigramsPerLiter(value); - case DensityUnit.DecigramPerMilliliter: - return FromDecigramsPerMilliliter(value); - case DensityUnit.GramPerCubicCentimeter: - return FromGramsPerCubicCentimeter(value); - case DensityUnit.GramPerCubicMeter: - return FromGramsPerCubicMeter(value); - case DensityUnit.GramPerCubicMillimeter: - return FromGramsPerCubicMillimeter(value); - case DensityUnit.GramPerDeciliter: - return FromGramsPerDeciLiter(value); - case DensityUnit.GramPerLiter: - return FromGramsPerLiter(value); - case DensityUnit.GramPerMilliliter: - return FromGramsPerMilliliter(value); - case DensityUnit.KilogramPerCubicCentimeter: - return FromKilogramsPerCubicCentimeter(value); - case DensityUnit.KilogramPerCubicMeter: - return FromKilogramsPerCubicMeter(value); - case DensityUnit.KilogramPerCubicMillimeter: - return FromKilogramsPerCubicMillimeter(value); - case DensityUnit.KilopoundPerCubicFoot: - return FromKilopoundsPerCubicFoot(value); - case DensityUnit.KilopoundPerCubicInch: - return FromKilopoundsPerCubicInch(value); - case DensityUnit.MicrogramPerDeciliter: - return FromMicrogramsPerDeciLiter(value); - case DensityUnit.MicrogramPerLiter: - return FromMicrogramsPerLiter(value); - case DensityUnit.MicrogramPerMilliliter: - return FromMicrogramsPerMilliliter(value); - case DensityUnit.MilligramPerCubicMeter: - return FromMilligramsPerCubicMeter(value); - case DensityUnit.MilligramPerDeciliter: - return FromMilligramsPerDeciLiter(value); - case DensityUnit.MilligramPerLiter: - return FromMilligramsPerLiter(value); - case DensityUnit.MilligramPerMilliliter: - return FromMilligramsPerMilliliter(value); - case DensityUnit.NanogramPerDeciliter: - return FromNanogramsPerDeciLiter(value); - case DensityUnit.NanogramPerLiter: - return FromNanogramsPerLiter(value); - case DensityUnit.NanogramPerMilliliter: - return FromNanogramsPerMilliliter(value); - case DensityUnit.PicogramPerDeciliter: - return FromPicogramsPerDeciLiter(value); - case DensityUnit.PicogramPerLiter: - return FromPicogramsPerLiter(value); - case DensityUnit.PicogramPerMilliliter: - return FromPicogramsPerMilliliter(value); - case DensityUnit.PoundPerCubicFoot: - return FromPoundsPerCubicFoot(value); - case DensityUnit.PoundPerCubicInch: - return FromPoundsPerCubicInch(value); - case DensityUnit.PoundPerImperialGallon: - return FromPoundsPerImperialGallon(value); - case DensityUnit.PoundPerUSGallon: - return FromPoundsPerUSGallon(value); - case DensityUnit.SlugPerCubicFoot: - return FromSlugsPerCubicFoot(value); - case DensityUnit.TonnePerCubicCentimeter: - return FromTonnesPerCubicCentimeter(value); - case DensityUnit.TonnePerCubicMeter: - return FromTonnesPerCubicMeter(value); - case DensityUnit.TonnePerCubicMillimeter: - return FromTonnesPerCubicMillimeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Density((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1812,88 +1458,8 @@ public static Density From(QuantityValue value, DensityUnit fromUnit) { return null; } - switch (fromUnit) - { - case DensityUnit.CentigramPerDeciliter: - return FromCentigramsPerDeciLiter(value.Value); - case DensityUnit.CentigramPerLiter: - return FromCentigramsPerLiter(value.Value); - case DensityUnit.CentigramPerMilliliter: - return FromCentigramsPerMilliliter(value.Value); - case DensityUnit.DecigramPerDeciliter: - return FromDecigramsPerDeciLiter(value.Value); - case DensityUnit.DecigramPerLiter: - return FromDecigramsPerLiter(value.Value); - case DensityUnit.DecigramPerMilliliter: - return FromDecigramsPerMilliliter(value.Value); - case DensityUnit.GramPerCubicCentimeter: - return FromGramsPerCubicCentimeter(value.Value); - case DensityUnit.GramPerCubicMeter: - return FromGramsPerCubicMeter(value.Value); - case DensityUnit.GramPerCubicMillimeter: - return FromGramsPerCubicMillimeter(value.Value); - case DensityUnit.GramPerDeciliter: - return FromGramsPerDeciLiter(value.Value); - case DensityUnit.GramPerLiter: - return FromGramsPerLiter(value.Value); - case DensityUnit.GramPerMilliliter: - return FromGramsPerMilliliter(value.Value); - case DensityUnit.KilogramPerCubicCentimeter: - return FromKilogramsPerCubicCentimeter(value.Value); - case DensityUnit.KilogramPerCubicMeter: - return FromKilogramsPerCubicMeter(value.Value); - case DensityUnit.KilogramPerCubicMillimeter: - return FromKilogramsPerCubicMillimeter(value.Value); - case DensityUnit.KilopoundPerCubicFoot: - return FromKilopoundsPerCubicFoot(value.Value); - case DensityUnit.KilopoundPerCubicInch: - return FromKilopoundsPerCubicInch(value.Value); - case DensityUnit.MicrogramPerDeciliter: - return FromMicrogramsPerDeciLiter(value.Value); - case DensityUnit.MicrogramPerLiter: - return FromMicrogramsPerLiter(value.Value); - case DensityUnit.MicrogramPerMilliliter: - return FromMicrogramsPerMilliliter(value.Value); - case DensityUnit.MilligramPerCubicMeter: - return FromMilligramsPerCubicMeter(value.Value); - case DensityUnit.MilligramPerDeciliter: - return FromMilligramsPerDeciLiter(value.Value); - case DensityUnit.MilligramPerLiter: - return FromMilligramsPerLiter(value.Value); - case DensityUnit.MilligramPerMilliliter: - return FromMilligramsPerMilliliter(value.Value); - case DensityUnit.NanogramPerDeciliter: - return FromNanogramsPerDeciLiter(value.Value); - case DensityUnit.NanogramPerLiter: - return FromNanogramsPerLiter(value.Value); - case DensityUnit.NanogramPerMilliliter: - return FromNanogramsPerMilliliter(value.Value); - case DensityUnit.PicogramPerDeciliter: - return FromPicogramsPerDeciLiter(value.Value); - case DensityUnit.PicogramPerLiter: - return FromPicogramsPerLiter(value.Value); - case DensityUnit.PicogramPerMilliliter: - return FromPicogramsPerMilliliter(value.Value); - case DensityUnit.PoundPerCubicFoot: - return FromPoundsPerCubicFoot(value.Value); - case DensityUnit.PoundPerCubicInch: - return FromPoundsPerCubicInch(value.Value); - case DensityUnit.PoundPerImperialGallon: - return FromPoundsPerImperialGallon(value.Value); - case DensityUnit.PoundPerUSGallon: - return FromPoundsPerUSGallon(value.Value); - case DensityUnit.SlugPerCubicFoot: - return FromSlugsPerCubicFoot(value.Value); - case DensityUnit.TonnePerCubicCentimeter: - return FromTonnesPerCubicCentimeter(value.Value); - case DensityUnit.TonnePerCubicMeter: - return FromTonnesPerCubicMeter(value.Value); - case DensityUnit.TonnePerCubicMillimeter: - return FromTonnesPerCubicMillimeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Density((double)value.Value, fromUnit); } #endif @@ -1912,12 +1478,29 @@ public static string GetAbbreviation(DensityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(DensityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + DensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1928,37 +1511,37 @@ public static string GetAbbreviation(DensityUnit unit, [CanBeNull] Culture cultu #if !WINDOWS_UWP public static Density operator -(Density right) { - return new Density(-right._kilogramsPerCubicMeter); + return new Density(-right.Value, right.Unit); } public static Density operator +(Density left, Density right) { - return new Density(left._kilogramsPerCubicMeter + right._kilogramsPerCubicMeter); + return new Density(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Density operator -(Density left, Density right) { - return new Density(left._kilogramsPerCubicMeter - right._kilogramsPerCubicMeter); + return new Density(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Density operator *(double left, Density right) { - return new Density(left*right._kilogramsPerCubicMeter); + return new Density(left * right.Value, right.Unit); } public static Density operator *(Density left, double right) { - return new Density(left._kilogramsPerCubicMeter*(double)right); + return new Density(left.Value * right, left.Unit); } public static Density operator /(Density left, double right) { - return new Density(left._kilogramsPerCubicMeter/(double)right); + return new Density(left.Value / right, left.Unit); } public static double operator /(Density left, Density right) { - return Convert.ToDouble(left._kilogramsPerCubicMeter/right._kilogramsPerCubicMeter); + return left.KilogramsPerCubicMeter / right.KilogramsPerCubicMeter; } #endif @@ -1981,43 +1564,43 @@ public int CompareTo(object obj) #endif int CompareTo(Density other) { - return _kilogramsPerCubicMeter.CompareTo(other._kilogramsPerCubicMeter); + return AsBaseUnitKilogramsPerCubicMeter().CompareTo(other.AsBaseUnitKilogramsPerCubicMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Density left, Density right) { - return left._kilogramsPerCubicMeter <= right._kilogramsPerCubicMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Density left, Density right) { - return left._kilogramsPerCubicMeter >= right._kilogramsPerCubicMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Density left, Density right) { - return left._kilogramsPerCubicMeter < right._kilogramsPerCubicMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Density left, Density right) { - return left._kilogramsPerCubicMeter > right._kilogramsPerCubicMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Density left, Density right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerCubicMeter == right._kilogramsPerCubicMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Density left, Density right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerCubicMeter != right._kilogramsPerCubicMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -2029,7 +1612,7 @@ public override bool Equals(object obj) return false; } - return _kilogramsPerCubicMeter.Equals(((Density) obj)._kilogramsPerCubicMeter); + return AsBaseUnitKilogramsPerCubicMeter().Equals(((Density) obj).AsBaseUnitKilogramsPerCubicMeter()); } /// @@ -2042,12 +1625,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Density other, Density maxError) { - return Math.Abs(_kilogramsPerCubicMeter - other._kilogramsPerCubicMeter) <= maxError._kilogramsPerCubicMeter; + return Math.Abs(AsBaseUnitKilogramsPerCubicMeter() - other.AsBaseUnitKilogramsPerCubicMeter()) <= maxError.AsBaseUnitKilogramsPerCubicMeter(); } public override int GetHashCode() { - return _kilogramsPerCubicMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -2057,88 +1640,56 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(DensityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitKilogramsPerCubicMeter(); + switch (unit) { - case DensityUnit.CentigramPerDeciliter: - return CentigramsPerDeciLiter; - case DensityUnit.CentigramPerLiter: - return CentigramsPerLiter; - case DensityUnit.CentigramPerMilliliter: - return CentigramsPerMilliliter; - case DensityUnit.DecigramPerDeciliter: - return DecigramsPerDeciLiter; - case DensityUnit.DecigramPerLiter: - return DecigramsPerLiter; - case DensityUnit.DecigramPerMilliliter: - return DecigramsPerMilliliter; - case DensityUnit.GramPerCubicCentimeter: - return GramsPerCubicCentimeter; - case DensityUnit.GramPerCubicMeter: - return GramsPerCubicMeter; - case DensityUnit.GramPerCubicMillimeter: - return GramsPerCubicMillimeter; - case DensityUnit.GramPerDeciliter: - return GramsPerDeciLiter; - case DensityUnit.GramPerLiter: - return GramsPerLiter; - case DensityUnit.GramPerMilliliter: - return GramsPerMilliliter; - case DensityUnit.KilogramPerCubicCentimeter: - return KilogramsPerCubicCentimeter; - case DensityUnit.KilogramPerCubicMeter: - return KilogramsPerCubicMeter; - case DensityUnit.KilogramPerCubicMillimeter: - return KilogramsPerCubicMillimeter; - case DensityUnit.KilopoundPerCubicFoot: - return KilopoundsPerCubicFoot; - case DensityUnit.KilopoundPerCubicInch: - return KilopoundsPerCubicInch; - case DensityUnit.MicrogramPerDeciliter: - return MicrogramsPerDeciLiter; - case DensityUnit.MicrogramPerLiter: - return MicrogramsPerLiter; - case DensityUnit.MicrogramPerMilliliter: - return MicrogramsPerMilliliter; - case DensityUnit.MilligramPerCubicMeter: - return MilligramsPerCubicMeter; - case DensityUnit.MilligramPerDeciliter: - return MilligramsPerDeciLiter; - case DensityUnit.MilligramPerLiter: - return MilligramsPerLiter; - case DensityUnit.MilligramPerMilliliter: - return MilligramsPerMilliliter; - case DensityUnit.NanogramPerDeciliter: - return NanogramsPerDeciLiter; - case DensityUnit.NanogramPerLiter: - return NanogramsPerLiter; - case DensityUnit.NanogramPerMilliliter: - return NanogramsPerMilliliter; - case DensityUnit.PicogramPerDeciliter: - return PicogramsPerDeciLiter; - case DensityUnit.PicogramPerLiter: - return PicogramsPerLiter; - case DensityUnit.PicogramPerMilliliter: - return PicogramsPerMilliliter; - case DensityUnit.PoundPerCubicFoot: - return PoundsPerCubicFoot; - case DensityUnit.PoundPerCubicInch: - return PoundsPerCubicInch; - case DensityUnit.PoundPerImperialGallon: - return PoundsPerImperialGallon; - case DensityUnit.PoundPerUSGallon: - return PoundsPerUSGallon; - case DensityUnit.SlugPerCubicFoot: - return SlugsPerCubicFoot; - case DensityUnit.TonnePerCubicCentimeter: - return TonnesPerCubicCentimeter; - case DensityUnit.TonnePerCubicMeter: - return TonnesPerCubicMeter; - case DensityUnit.TonnePerCubicMillimeter: - return TonnesPerCubicMillimeter; + case DensityUnit.CentigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-2d; + case DensityUnit.CentigramPerLiter: return (baseUnitValue*1) / 1e-2d; + case DensityUnit.CentigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-2d; + case DensityUnit.DecigramPerDeciliter: return (baseUnitValue*1e-1) / 1e-1d; + case DensityUnit.DecigramPerLiter: return (baseUnitValue*1) / 1e-1d; + case DensityUnit.DecigramPerMilliliter: return (baseUnitValue*1e-3) / 1e-1d; + case DensityUnit.GramPerCubicCentimeter: return baseUnitValue*1e-3; + case DensityUnit.GramPerCubicMeter: return baseUnitValue*1e3; + case DensityUnit.GramPerCubicMillimeter: return baseUnitValue*1e-6; + case DensityUnit.GramPerDeciliter: return baseUnitValue*1e-1; + case DensityUnit.GramPerLiter: return baseUnitValue*1; + case DensityUnit.GramPerMilliliter: return baseUnitValue*1e-3; + case DensityUnit.KilogramPerCubicCentimeter: return (baseUnitValue*1e-3) / 1e3d; + case DensityUnit.KilogramPerCubicMeter: return (baseUnitValue*1e3) / 1e3d; + case DensityUnit.KilogramPerCubicMillimeter: return (baseUnitValue*1e-6) / 1e3d; + case DensityUnit.KilopoundPerCubicFoot: return (baseUnitValue*0.062427961) / 1e3d; + case DensityUnit.KilopoundPerCubicInch: return (baseUnitValue*3.6127298147753e-5) / 1e3d; + case DensityUnit.MicrogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-6d; + case DensityUnit.MicrogramPerLiter: return (baseUnitValue*1) / 1e-6d; + case DensityUnit.MicrogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-6d; + case DensityUnit.MilligramPerCubicMeter: return (baseUnitValue*1e3) / 1e-3d; + case DensityUnit.MilligramPerDeciliter: return (baseUnitValue*1e-1) / 1e-3d; + case DensityUnit.MilligramPerLiter: return (baseUnitValue*1) / 1e-3d; + case DensityUnit.MilligramPerMilliliter: return (baseUnitValue*1e-3) / 1e-3d; + case DensityUnit.NanogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-9d; + case DensityUnit.NanogramPerLiter: return (baseUnitValue*1) / 1e-9d; + case DensityUnit.NanogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-9d; + case DensityUnit.PicogramPerDeciliter: return (baseUnitValue*1e-1) / 1e-12d; + case DensityUnit.PicogramPerLiter: return (baseUnitValue*1) / 1e-12d; + case DensityUnit.PicogramPerMilliliter: return (baseUnitValue*1e-3) / 1e-12d; + case DensityUnit.PoundPerCubicFoot: return baseUnitValue*0.062427961; + case DensityUnit.PoundPerCubicInch: return baseUnitValue*3.6127298147753e-5; + case DensityUnit.PoundPerImperialGallon: return baseUnitValue/9.9776398e1; + case DensityUnit.PoundPerUSGallon: return baseUnitValue/1.19826427e2; + case DensityUnit.SlugPerCubicFoot: return baseUnitValue*0.00194032033; + case DensityUnit.TonnePerCubicCentimeter: return baseUnitValue*1e-9; + case DensityUnit.TonnePerCubicMeter: return baseUnitValue*0.001; + case DensityUnit.TonnePerCubicMillimeter: return baseUnitValue*1e-12; default: throw new NotImplementedException("unit: " + unit); @@ -2180,7 +1731,11 @@ public static Density Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -2199,17 +1754,24 @@ public static Density Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Density Parse(string str, [CanBeNull] Culture culture) + public static Density Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -2235,16 +1797,41 @@ public static bool TryParse([CanBeNull] string str, out Density result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Density result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Density result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -2257,6 +1844,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -2270,11 +1858,14 @@ public static DensityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static DensityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -2283,6 +1874,8 @@ public static DensityUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -2295,18 +1888,18 @@ public static DensityUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static DensityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static DensityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == DensityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DensityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -2315,6 +1908,7 @@ static DensityUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is KilogramPerCubicMeter /// @@ -2326,7 +1920,7 @@ static DensityUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -2343,74 +1937,166 @@ public string ToString(DensityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(DensityUnit unit, [CanBeNull] Culture culture) + public string ToString( + DensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(DensityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + DensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(DensityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + DensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Density /// - public static Density MaxValue - { - get - { - return new Density(double.MaxValue); - } - } + public static Density MaxValue => new Density(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Density /// - public static Density MinValue - { - get - { - return new Density(double.MinValue); - } - } - } + public static Density MinValue => new Density(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitKilogramsPerCubicMeter() + { + if (Unit == DensityUnit.KilogramPerCubicMeter) { return _value; } + + switch (Unit) + { + case DensityUnit.CentigramPerDeciliter: return (_value/1e-1) * 1e-2d; + case DensityUnit.CentigramPerLiter: return (_value/1) * 1e-2d; + case DensityUnit.CentigramPerMilliliter: return (_value/1e-3) * 1e-2d; + case DensityUnit.DecigramPerDeciliter: return (_value/1e-1) * 1e-1d; + case DensityUnit.DecigramPerLiter: return (_value/1) * 1e-1d; + case DensityUnit.DecigramPerMilliliter: return (_value/1e-3) * 1e-1d; + case DensityUnit.GramPerCubicCentimeter: return _value/1e-3; + case DensityUnit.GramPerCubicMeter: return _value/1e3; + case DensityUnit.GramPerCubicMillimeter: return _value/1e-6; + case DensityUnit.GramPerDeciliter: return _value/1e-1; + case DensityUnit.GramPerLiter: return _value/1; + case DensityUnit.GramPerMilliliter: return _value/1e-3; + case DensityUnit.KilogramPerCubicCentimeter: return (_value/1e-3) * 1e3d; + case DensityUnit.KilogramPerCubicMeter: return (_value/1e3) * 1e3d; + case DensityUnit.KilogramPerCubicMillimeter: return (_value/1e-6) * 1e3d; + case DensityUnit.KilopoundPerCubicFoot: return (_value/0.062427961) * 1e3d; + case DensityUnit.KilopoundPerCubicInch: return (_value/3.6127298147753e-5) * 1e3d; + case DensityUnit.MicrogramPerDeciliter: return (_value/1e-1) * 1e-6d; + case DensityUnit.MicrogramPerLiter: return (_value/1) * 1e-6d; + case DensityUnit.MicrogramPerMilliliter: return (_value/1e-3) * 1e-6d; + case DensityUnit.MilligramPerCubicMeter: return (_value/1e3) * 1e-3d; + case DensityUnit.MilligramPerDeciliter: return (_value/1e-1) * 1e-3d; + case DensityUnit.MilligramPerLiter: return (_value/1) * 1e-3d; + case DensityUnit.MilligramPerMilliliter: return (_value/1e-3) * 1e-3d; + case DensityUnit.NanogramPerDeciliter: return (_value/1e-1) * 1e-9d; + case DensityUnit.NanogramPerLiter: return (_value/1) * 1e-9d; + case DensityUnit.NanogramPerMilliliter: return (_value/1e-3) * 1e-9d; + case DensityUnit.PicogramPerDeciliter: return (_value/1e-1) * 1e-12d; + case DensityUnit.PicogramPerLiter: return (_value/1) * 1e-12d; + case DensityUnit.PicogramPerMilliliter: return (_value/1e-3) * 1e-12d; + case DensityUnit.PoundPerCubicFoot: return _value/0.062427961; + case DensityUnit.PoundPerCubicInch: return _value/3.6127298147753e-5; + case DensityUnit.PoundPerImperialGallon: return _value*9.9776398e1; + case DensityUnit.PoundPerUSGallon: return _value*1.19826427e2; + case DensityUnit.SlugPerCubicFoot: return _value*515.378818; + case DensityUnit.TonnePerCubicCentimeter: return _value/1e-9; + case DensityUnit.TonnePerCubicMeter: return _value/0.001; + case DensityUnit.TonnePerCubicMillimeter: return _value/1e-12; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(DensityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs index ab133b7040..f5f5f74d76 100644 --- a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Duration : IComparable, IComparable #endif { /// - /// Base unit of Duration. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _seconds; + private readonly DurationUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Duration() : this(0) + public Duration() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Duration(double seconds) { - _seconds = Convert.ToDouble(seconds); + _value = Convert.ToDouble(seconds); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Duration(double numericValue, DurationUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Second. + /// + /// Value assuming base unit Second. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Duration(long seconds) - { - _seconds = Convert.ToDouble(seconds); - } + Duration(long seconds) : this(Convert.ToDouble(seconds), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Second. + /// + /// Value assuming base unit Second. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Duration(decimal seconds) - { - _seconds = Convert.ToDouble(seconds); - } + Duration(decimal seconds) : this(Convert.ToDouble(seconds), BaseUnit) { } #region Properties @@ -119,122 +156,68 @@ public Duration(double seconds) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static DurationUnit BaseUnit - { - get { return DurationUnit.Second; } - } + public static DurationUnit BaseUnit => DurationUnit.Second; /// /// All units of measurement for the Duration quantity. /// public static DurationUnit[] Units { get; } = Enum.GetValues(typeof(DurationUnit)).Cast().ToArray(); - /// /// Get Duration in Days. /// - public double Days - { - get { return _seconds/(24*3600); } - } - + public double Days => As(DurationUnit.Day); /// /// Get Duration in Hours. /// - public double Hours - { - get { return _seconds/3600; } - } - + public double Hours => As(DurationUnit.Hour); /// /// Get Duration in Microseconds. /// - public double Microseconds - { - get { return (_seconds) / 1e-6d; } - } - + public double Microseconds => As(DurationUnit.Microsecond); /// /// Get Duration in Milliseconds. /// - public double Milliseconds - { - get { return (_seconds) / 1e-3d; } - } - + public double Milliseconds => As(DurationUnit.Millisecond); /// /// Get Duration in Minutes. /// - public double Minutes - { - get { return _seconds/60; } - } - + public double Minutes => As(DurationUnit.Minute); /// /// Get Duration in Months. /// [System.Obsolete("Use Month30 instead, which makes it clear that this is an approximate unit based on 30 days per month. The duration of a month varies, but the Gregorian solar calendar has 365.2425/12 = 30.44 days on average.")] - public double Months - { - get { return _seconds/(30*24*3600); } - } - + public double Months => As(DurationUnit.Month); /// /// Get Duration in Months30. /// - public double Months30 - { - get { return _seconds/(30*24*3600); } - } - + public double Months30 => As(DurationUnit.Month30); /// /// Get Duration in Nanoseconds. /// - public double Nanoseconds - { - get { return (_seconds) / 1e-9d; } - } - + public double Nanoseconds => As(DurationUnit.Nanosecond); /// /// Get Duration in Seconds. /// - public double Seconds - { - get { return _seconds; } - } - + public double Seconds => As(DurationUnit.Second); /// /// Get Duration in Weeks. /// - public double Weeks - { - get { return _seconds/(7*24*3600); } - } - + public double Weeks => As(DurationUnit.Week); /// /// Get Duration in Years. /// [System.Obsolete("Use Year365 instead, which makes it clear that this is an approximate unit based on 365 days per year. The duration of a year varies due to corrections such as leap years, since a Gregorian solar calendar has 365.2425 days.")] - public double Years - { - get { return _seconds/(365*24*3600); } - } - + public double Years => As(DurationUnit.Year); /// /// Get Duration in Years365. /// - public double Years365 - { - get { return _seconds/(365*24*3600); } - } + public double Years365 => As(DurationUnit.Year365); #endregion #region Static - public static Duration Zero - { - get { return new Duration(); } - } + public static Duration Zero => new Duration(0, BaseUnit); /// /// Get Duration from Days. @@ -242,17 +225,13 @@ public static Duration Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromDays(double days) - { - double value = (double) days; - return new Duration(value*24*3600); - } #else public static Duration FromDays(QuantityValue days) +#endif { double value = (double) days; - return new Duration((value*24*3600)); + return new Duration(value, DurationUnit.Day); } -#endif /// /// Get Duration from Hours. @@ -260,17 +239,13 @@ public static Duration FromDays(QuantityValue days) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromHours(double hours) - { - double value = (double) hours; - return new Duration(value*3600); - } #else public static Duration FromHours(QuantityValue hours) +#endif { double value = (double) hours; - return new Duration((value*3600)); + return new Duration(value, DurationUnit.Hour); } -#endif /// /// Get Duration from Microseconds. @@ -278,17 +253,13 @@ public static Duration FromHours(QuantityValue hours) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromMicroseconds(double microseconds) - { - double value = (double) microseconds; - return new Duration((value) * 1e-6d); - } #else public static Duration FromMicroseconds(QuantityValue microseconds) +#endif { double value = (double) microseconds; - return new Duration(((value) * 1e-6d)); + return new Duration(value, DurationUnit.Microsecond); } -#endif /// /// Get Duration from Milliseconds. @@ -296,17 +267,13 @@ public static Duration FromMicroseconds(QuantityValue microseconds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromMilliseconds(double milliseconds) - { - double value = (double) milliseconds; - return new Duration((value) * 1e-3d); - } #else public static Duration FromMilliseconds(QuantityValue milliseconds) +#endif { double value = (double) milliseconds; - return new Duration(((value) * 1e-3d)); + return new Duration(value, DurationUnit.Millisecond); } -#endif /// /// Get Duration from Minutes. @@ -314,17 +281,13 @@ public static Duration FromMilliseconds(QuantityValue milliseconds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromMinutes(double minutes) - { - double value = (double) minutes; - return new Duration(value*60); - } #else public static Duration FromMinutes(QuantityValue minutes) +#endif { double value = (double) minutes; - return new Duration((value*60)); + return new Duration(value, DurationUnit.Minute); } -#endif /// /// Get Duration from Months. @@ -332,17 +295,13 @@ public static Duration FromMinutes(QuantityValue minutes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromMonths(double months) - { - double value = (double) months; - return new Duration(value*30*24*3600); - } #else public static Duration FromMonths(QuantityValue months) +#endif { double value = (double) months; - return new Duration((value*30*24*3600)); + return new Duration(value, DurationUnit.Month); } -#endif /// /// Get Duration from Months30. @@ -350,17 +309,13 @@ public static Duration FromMonths(QuantityValue months) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromMonths30(double months30) - { - double value = (double) months30; - return new Duration(value*30*24*3600); - } #else public static Duration FromMonths30(QuantityValue months30) +#endif { double value = (double) months30; - return new Duration((value*30*24*3600)); + return new Duration(value, DurationUnit.Month30); } -#endif /// /// Get Duration from Nanoseconds. @@ -368,17 +323,13 @@ public static Duration FromMonths30(QuantityValue months30) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromNanoseconds(double nanoseconds) - { - double value = (double) nanoseconds; - return new Duration((value) * 1e-9d); - } #else public static Duration FromNanoseconds(QuantityValue nanoseconds) +#endif { double value = (double) nanoseconds; - return new Duration(((value) * 1e-9d)); + return new Duration(value, DurationUnit.Nanosecond); } -#endif /// /// Get Duration from Seconds. @@ -386,17 +337,13 @@ public static Duration FromNanoseconds(QuantityValue nanoseconds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromSeconds(double seconds) - { - double value = (double) seconds; - return new Duration(value); - } #else public static Duration FromSeconds(QuantityValue seconds) +#endif { double value = (double) seconds; - return new Duration((value)); + return new Duration(value, DurationUnit.Second); } -#endif /// /// Get Duration from Weeks. @@ -404,17 +351,13 @@ public static Duration FromSeconds(QuantityValue seconds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromWeeks(double weeks) - { - double value = (double) weeks; - return new Duration(value*7*24*3600); - } #else public static Duration FromWeeks(QuantityValue weeks) +#endif { double value = (double) weeks; - return new Duration((value*7*24*3600)); + return new Duration(value, DurationUnit.Week); } -#endif /// /// Get Duration from Years. @@ -422,17 +365,13 @@ public static Duration FromWeeks(QuantityValue weeks) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromYears(double years) - { - double value = (double) years; - return new Duration(value*365*24*3600); - } #else public static Duration FromYears(QuantityValue years) +#endif { double value = (double) years; - return new Duration((value*365*24*3600)); + return new Duration(value, DurationUnit.Year); } -#endif /// /// Get Duration from Years365. @@ -440,17 +379,13 @@ public static Duration FromYears(QuantityValue years) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Duration FromYears365(double years365) - { - double value = (double) years365; - return new Duration(value*365*24*3600); - } #else public static Duration FromYears365(QuantityValue years365) +#endif { double value = (double) years365; - return new Duration((value*365*24*3600)); + return new Duration(value, DurationUnit.Year365); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -650,36 +585,7 @@ public static Duration From(double value, DurationUnit fromUnit) public static Duration From(QuantityValue value, DurationUnit fromUnit) #endif { - switch (fromUnit) - { - case DurationUnit.Day: - return FromDays(value); - case DurationUnit.Hour: - return FromHours(value); - case DurationUnit.Microsecond: - return FromMicroseconds(value); - case DurationUnit.Millisecond: - return FromMilliseconds(value); - case DurationUnit.Minute: - return FromMinutes(value); - case DurationUnit.Month: - return FromMonths(value); - case DurationUnit.Month30: - return FromMonths30(value); - case DurationUnit.Nanosecond: - return FromNanoseconds(value); - case DurationUnit.Second: - return FromSeconds(value); - case DurationUnit.Week: - return FromWeeks(value); - case DurationUnit.Year: - return FromYears(value); - case DurationUnit.Year365: - return FromYears365(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Duration((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -696,36 +602,8 @@ public static Duration From(QuantityValue value, DurationUnit fromUnit) { return null; } - switch (fromUnit) - { - case DurationUnit.Day: - return FromDays(value.Value); - case DurationUnit.Hour: - return FromHours(value.Value); - case DurationUnit.Microsecond: - return FromMicroseconds(value.Value); - case DurationUnit.Millisecond: - return FromMilliseconds(value.Value); - case DurationUnit.Minute: - return FromMinutes(value.Value); - case DurationUnit.Month: - return FromMonths(value.Value); - case DurationUnit.Month30: - return FromMonths30(value.Value); - case DurationUnit.Nanosecond: - return FromNanoseconds(value.Value); - case DurationUnit.Second: - return FromSeconds(value.Value); - case DurationUnit.Week: - return FromWeeks(value.Value); - case DurationUnit.Year: - return FromYears(value.Value); - case DurationUnit.Year365: - return FromYears365(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Duration((double)value.Value, fromUnit); } #endif @@ -744,12 +622,29 @@ public static string GetAbbreviation(DurationUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(DurationUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + DurationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -760,37 +655,37 @@ public static string GetAbbreviation(DurationUnit unit, [CanBeNull] Culture cult #if !WINDOWS_UWP public static Duration operator -(Duration right) { - return new Duration(-right._seconds); + return new Duration(-right.Value, right.Unit); } public static Duration operator +(Duration left, Duration right) { - return new Duration(left._seconds + right._seconds); + return new Duration(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Duration operator -(Duration left, Duration right) { - return new Duration(left._seconds - right._seconds); + return new Duration(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Duration operator *(double left, Duration right) { - return new Duration(left*right._seconds); + return new Duration(left * right.Value, right.Unit); } public static Duration operator *(Duration left, double right) { - return new Duration(left._seconds*(double)right); + return new Duration(left.Value * right, left.Unit); } public static Duration operator /(Duration left, double right) { - return new Duration(left._seconds/(double)right); + return new Duration(left.Value / right, left.Unit); } public static double operator /(Duration left, Duration right) { - return Convert.ToDouble(left._seconds/right._seconds); + return left.Seconds / right.Seconds; } #endif @@ -813,43 +708,43 @@ public int CompareTo(object obj) #endif int CompareTo(Duration other) { - return _seconds.CompareTo(other._seconds); + return AsBaseUnitSeconds().CompareTo(other.AsBaseUnitSeconds()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Duration left, Duration right) { - return left._seconds <= right._seconds; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Duration left, Duration right) { - return left._seconds >= right._seconds; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Duration left, Duration right) { - return left._seconds < right._seconds; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Duration left, Duration right) { - return left._seconds > right._seconds; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Duration left, Duration right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._seconds == right._seconds; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Duration left, Duration right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._seconds != right._seconds; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -861,7 +756,7 @@ public override bool Equals(object obj) return false; } - return _seconds.Equals(((Duration) obj)._seconds); + return AsBaseUnitSeconds().Equals(((Duration) obj).AsBaseUnitSeconds()); } /// @@ -874,12 +769,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Duration other, Duration maxError) { - return Math.Abs(_seconds - other._seconds) <= maxError._seconds; + return Math.Abs(AsBaseUnitSeconds() - other.AsBaseUnitSeconds()) <= maxError.AsBaseUnitSeconds(); } public override int GetHashCode() { - return _seconds.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -889,36 +784,30 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(DurationUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitSeconds(); + switch (unit) { - case DurationUnit.Day: - return Days; - case DurationUnit.Hour: - return Hours; - case DurationUnit.Microsecond: - return Microseconds; - case DurationUnit.Millisecond: - return Milliseconds; - case DurationUnit.Minute: - return Minutes; - case DurationUnit.Month: - return Months; - case DurationUnit.Month30: - return Months30; - case DurationUnit.Nanosecond: - return Nanoseconds; - case DurationUnit.Second: - return Seconds; - case DurationUnit.Week: - return Weeks; - case DurationUnit.Year: - return Years; - case DurationUnit.Year365: - return Years365; + case DurationUnit.Day: return baseUnitValue/(24*3600); + case DurationUnit.Hour: return baseUnitValue/3600; + case DurationUnit.Microsecond: return (baseUnitValue) / 1e-6d; + case DurationUnit.Millisecond: return (baseUnitValue) / 1e-3d; + case DurationUnit.Minute: return baseUnitValue/60; + case DurationUnit.Month: return baseUnitValue/(30*24*3600); + case DurationUnit.Month30: return baseUnitValue/(30*24*3600); + case DurationUnit.Nanosecond: return (baseUnitValue) / 1e-9d; + case DurationUnit.Second: return baseUnitValue; + case DurationUnit.Week: return baseUnitValue/(7*24*3600); + case DurationUnit.Year: return baseUnitValue/(365*24*3600); + case DurationUnit.Year365: return baseUnitValue/(365*24*3600); default: throw new NotImplementedException("unit: " + unit); @@ -960,7 +849,11 @@ public static Duration Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -979,17 +872,24 @@ public static Duration Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Duration Parse(string str, [CanBeNull] Culture culture) + public static Duration Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1015,16 +915,41 @@ public static bool TryParse([CanBeNull] string str, out Duration result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Duration result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Duration result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1037,6 +962,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1050,11 +976,14 @@ public static DurationUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static DurationUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1063,6 +992,8 @@ public static DurationUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1075,18 +1006,18 @@ public static DurationUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static DurationUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static DurationUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == DurationUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DurationUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1095,6 +1026,7 @@ static DurationUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Second /// @@ -1106,7 +1038,7 @@ static DurationUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1123,74 +1055,140 @@ public string ToString(DurationUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(DurationUnit unit, [CanBeNull] Culture culture) + public string ToString( + DurationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(DurationUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + DurationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(DurationUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + DurationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Duration /// - public static Duration MaxValue - { - get - { - return new Duration(double.MaxValue); - } - } + public static Duration MaxValue => new Duration(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Duration /// - public static Duration MinValue + public static Duration MinValue => new Duration(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitSeconds() { - get + if (Unit == DurationUnit.Second) { return _value; } + + switch (Unit) { - return new Duration(double.MinValue); - } - } - } + case DurationUnit.Day: return _value*24*3600; + case DurationUnit.Hour: return _value*3600; + case DurationUnit.Microsecond: return (_value) * 1e-6d; + case DurationUnit.Millisecond: return (_value) * 1e-3d; + case DurationUnit.Minute: return _value*60; + case DurationUnit.Month: return _value*30*24*3600; + case DurationUnit.Month30: return _value*30*24*3600; + case DurationUnit.Nanosecond: return (_value) * 1e-9d; + case DurationUnit.Second: return _value; + case DurationUnit.Week: return _value*7*24*3600; + case DurationUnit.Year: return _value*365*24*3600; + case DurationUnit.Year365: return _value*365*24*3600; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(DurationUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs index 21e05401b1..42219acd12 100644 --- a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct DynamicViscosity : IComparable, IComparable - /// Base unit of DynamicViscosity. + /// The numeric value this quantity was constructed with. /// - private readonly double _newtonSecondsPerMeterSquared; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly DynamicViscosityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public DynamicViscosity() : this(0) + public DynamicViscosity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public DynamicViscosity(double newtonsecondspermetersquared) { - _newtonSecondsPerMeterSquared = Convert.ToDouble(newtonsecondspermetersquared); + _value = Convert.ToDouble(newtonsecondspermetersquared); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + DynamicViscosity(double numericValue, DynamicViscosityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit NewtonSecondPerMeterSquared. + /// + /// Value assuming base unit NewtonSecondPerMeterSquared. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - DynamicViscosity(long newtonsecondspermetersquared) - { - _newtonSecondsPerMeterSquared = Convert.ToDouble(newtonsecondspermetersquared); - } + DynamicViscosity(long newtonsecondspermetersquared) : this(Convert.ToDouble(newtonsecondspermetersquared), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit NewtonSecondPerMeterSquared. + /// + /// Value assuming base unit NewtonSecondPerMeterSquared. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - DynamicViscosity(decimal newtonsecondspermetersquared) - { - _newtonSecondsPerMeterSquared = Convert.ToDouble(newtonsecondspermetersquared); - } + DynamicViscosity(decimal newtonsecondspermetersquared) : this(Convert.ToDouble(newtonsecondspermetersquared), BaseUnit) { } #region Properties @@ -119,72 +156,42 @@ public DynamicViscosity(double newtonsecondspermetersquared) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static DynamicViscosityUnit BaseUnit - { - get { return DynamicViscosityUnit.NewtonSecondPerMeterSquared; } - } + public static DynamicViscosityUnit BaseUnit => DynamicViscosityUnit.NewtonSecondPerMeterSquared; /// /// All units of measurement for the DynamicViscosity quantity. /// public static DynamicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().ToArray(); - /// /// Get DynamicViscosity in Centipoise. /// - public double Centipoise - { - get { return (_newtonSecondsPerMeterSquared*10) / 1e-2d; } - } - + public double Centipoise => As(DynamicViscosityUnit.Centipoise); /// /// Get DynamicViscosity in MicropascalSeconds. /// - public double MicropascalSeconds - { - get { return (_newtonSecondsPerMeterSquared) / 1e-6d; } - } - + public double MicropascalSeconds => As(DynamicViscosityUnit.MicropascalSecond); /// /// Get DynamicViscosity in MillipascalSeconds. /// - public double MillipascalSeconds - { - get { return (_newtonSecondsPerMeterSquared) / 1e-3d; } - } - + public double MillipascalSeconds => As(DynamicViscosityUnit.MillipascalSecond); /// /// Get DynamicViscosity in NewtonSecondsPerMeterSquared. /// - public double NewtonSecondsPerMeterSquared - { - get { return _newtonSecondsPerMeterSquared; } - } - + public double NewtonSecondsPerMeterSquared => As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); /// /// Get DynamicViscosity in PascalSeconds. /// - public double PascalSeconds - { - get { return _newtonSecondsPerMeterSquared; } - } - + public double PascalSeconds => As(DynamicViscosityUnit.PascalSecond); /// /// Get DynamicViscosity in Poise. /// - public double Poise - { - get { return _newtonSecondsPerMeterSquared*10; } - } + public double Poise => As(DynamicViscosityUnit.Poise); #endregion #region Static - public static DynamicViscosity Zero - { - get { return new DynamicViscosity(); } - } + public static DynamicViscosity Zero => new DynamicViscosity(0, BaseUnit); /// /// Get DynamicViscosity from Centipoise. @@ -192,17 +199,13 @@ public static DynamicViscosity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static DynamicViscosity FromCentipoise(double centipoise) - { - double value = (double) centipoise; - return new DynamicViscosity((value/10) * 1e-2d); - } #else public static DynamicViscosity FromCentipoise(QuantityValue centipoise) +#endif { double value = (double) centipoise; - return new DynamicViscosity(((value/10) * 1e-2d)); + return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); } -#endif /// /// Get DynamicViscosity from MicropascalSeconds. @@ -210,17 +213,13 @@ public static DynamicViscosity FromCentipoise(QuantityValue centipoise) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static DynamicViscosity FromMicropascalSeconds(double micropascalseconds) - { - double value = (double) micropascalseconds; - return new DynamicViscosity((value) * 1e-6d); - } #else public static DynamicViscosity FromMicropascalSeconds(QuantityValue micropascalseconds) +#endif { double value = (double) micropascalseconds; - return new DynamicViscosity(((value) * 1e-6d)); + return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); } -#endif /// /// Get DynamicViscosity from MillipascalSeconds. @@ -228,17 +227,13 @@ public static DynamicViscosity FromMicropascalSeconds(QuantityValue micropascals #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static DynamicViscosity FromMillipascalSeconds(double millipascalseconds) - { - double value = (double) millipascalseconds; - return new DynamicViscosity((value) * 1e-3d); - } #else public static DynamicViscosity FromMillipascalSeconds(QuantityValue millipascalseconds) +#endif { double value = (double) millipascalseconds; - return new DynamicViscosity(((value) * 1e-3d)); + return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); } -#endif /// /// Get DynamicViscosity from NewtonSecondsPerMeterSquared. @@ -246,17 +241,13 @@ public static DynamicViscosity FromMillipascalSeconds(QuantityValue millipascals #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static DynamicViscosity FromNewtonSecondsPerMeterSquared(double newtonsecondspermetersquared) - { - double value = (double) newtonsecondspermetersquared; - return new DynamicViscosity(value); - } #else public static DynamicViscosity FromNewtonSecondsPerMeterSquared(QuantityValue newtonsecondspermetersquared) +#endif { double value = (double) newtonsecondspermetersquared; - return new DynamicViscosity((value)); + return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); } -#endif /// /// Get DynamicViscosity from PascalSeconds. @@ -264,17 +255,13 @@ public static DynamicViscosity FromNewtonSecondsPerMeterSquared(QuantityValue ne #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static DynamicViscosity FromPascalSeconds(double pascalseconds) - { - double value = (double) pascalseconds; - return new DynamicViscosity(value); - } #else public static DynamicViscosity FromPascalSeconds(QuantityValue pascalseconds) +#endif { double value = (double) pascalseconds; - return new DynamicViscosity((value)); + return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); } -#endif /// /// Get DynamicViscosity from Poise. @@ -282,17 +269,13 @@ public static DynamicViscosity FromPascalSeconds(QuantityValue pascalseconds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static DynamicViscosity FromPoise(double poise) - { - double value = (double) poise; - return new DynamicViscosity(value/10); - } #else public static DynamicViscosity FromPoise(QuantityValue poise) +#endif { double value = (double) poise; - return new DynamicViscosity((value/10)); + return new DynamicViscosity(value, DynamicViscosityUnit.Poise); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -402,24 +385,7 @@ public static DynamicViscosity From(double value, DynamicViscosityUnit fromUnit) public static DynamicViscosity From(QuantityValue value, DynamicViscosityUnit fromUnit) #endif { - switch (fromUnit) - { - case DynamicViscosityUnit.Centipoise: - return FromCentipoise(value); - case DynamicViscosityUnit.MicropascalSecond: - return FromMicropascalSeconds(value); - case DynamicViscosityUnit.MillipascalSecond: - return FromMillipascalSeconds(value); - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: - return FromNewtonSecondsPerMeterSquared(value); - case DynamicViscosityUnit.PascalSecond: - return FromPascalSeconds(value); - case DynamicViscosityUnit.Poise: - return FromPoise(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new DynamicViscosity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -436,24 +402,8 @@ public static DynamicViscosity From(QuantityValue value, DynamicViscosityUnit fr { return null; } - switch (fromUnit) - { - case DynamicViscosityUnit.Centipoise: - return FromCentipoise(value.Value); - case DynamicViscosityUnit.MicropascalSecond: - return FromMicropascalSeconds(value.Value); - case DynamicViscosityUnit.MillipascalSecond: - return FromMillipascalSeconds(value.Value); - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: - return FromNewtonSecondsPerMeterSquared(value.Value); - case DynamicViscosityUnit.PascalSecond: - return FromPascalSeconds(value.Value); - case DynamicViscosityUnit.Poise: - return FromPoise(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new DynamicViscosity((double)value.Value, fromUnit); } #endif @@ -472,12 +422,29 @@ public static string GetAbbreviation(DynamicViscosityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(DynamicViscosityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + DynamicViscosityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -488,37 +455,37 @@ public static string GetAbbreviation(DynamicViscosityUnit unit, [CanBeNull] Cult #if !WINDOWS_UWP public static DynamicViscosity operator -(DynamicViscosity right) { - return new DynamicViscosity(-right._newtonSecondsPerMeterSquared); + return new DynamicViscosity(-right.Value, right.Unit); } public static DynamicViscosity operator +(DynamicViscosity left, DynamicViscosity right) { - return new DynamicViscosity(left._newtonSecondsPerMeterSquared + right._newtonSecondsPerMeterSquared); + return new DynamicViscosity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static DynamicViscosity operator -(DynamicViscosity left, DynamicViscosity right) { - return new DynamicViscosity(left._newtonSecondsPerMeterSquared - right._newtonSecondsPerMeterSquared); + return new DynamicViscosity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static DynamicViscosity operator *(double left, DynamicViscosity right) { - return new DynamicViscosity(left*right._newtonSecondsPerMeterSquared); + return new DynamicViscosity(left * right.Value, right.Unit); } public static DynamicViscosity operator *(DynamicViscosity left, double right) { - return new DynamicViscosity(left._newtonSecondsPerMeterSquared*(double)right); + return new DynamicViscosity(left.Value * right, left.Unit); } public static DynamicViscosity operator /(DynamicViscosity left, double right) { - return new DynamicViscosity(left._newtonSecondsPerMeterSquared/(double)right); + return new DynamicViscosity(left.Value / right, left.Unit); } public static double operator /(DynamicViscosity left, DynamicViscosity right) { - return Convert.ToDouble(left._newtonSecondsPerMeterSquared/right._newtonSecondsPerMeterSquared); + return left.NewtonSecondsPerMeterSquared / right.NewtonSecondsPerMeterSquared; } #endif @@ -541,43 +508,43 @@ public int CompareTo(object obj) #endif int CompareTo(DynamicViscosity other) { - return _newtonSecondsPerMeterSquared.CompareTo(other._newtonSecondsPerMeterSquared); + return AsBaseUnitNewtonSecondsPerMeterSquared().CompareTo(other.AsBaseUnitNewtonSecondsPerMeterSquared()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(DynamicViscosity left, DynamicViscosity right) { - return left._newtonSecondsPerMeterSquared <= right._newtonSecondsPerMeterSquared; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(DynamicViscosity left, DynamicViscosity right) { - return left._newtonSecondsPerMeterSquared >= right._newtonSecondsPerMeterSquared; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(DynamicViscosity left, DynamicViscosity right) { - return left._newtonSecondsPerMeterSquared < right._newtonSecondsPerMeterSquared; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(DynamicViscosity left, DynamicViscosity right) { - return left._newtonSecondsPerMeterSquared > right._newtonSecondsPerMeterSquared; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(DynamicViscosity left, DynamicViscosity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtonSecondsPerMeterSquared == right._newtonSecondsPerMeterSquared; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(DynamicViscosity left, DynamicViscosity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtonSecondsPerMeterSquared != right._newtonSecondsPerMeterSquared; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -589,7 +556,7 @@ public override bool Equals(object obj) return false; } - return _newtonSecondsPerMeterSquared.Equals(((DynamicViscosity) obj)._newtonSecondsPerMeterSquared); + return AsBaseUnitNewtonSecondsPerMeterSquared().Equals(((DynamicViscosity) obj).AsBaseUnitNewtonSecondsPerMeterSquared()); } /// @@ -602,12 +569,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(DynamicViscosity other, DynamicViscosity maxError) { - return Math.Abs(_newtonSecondsPerMeterSquared - other._newtonSecondsPerMeterSquared) <= maxError._newtonSecondsPerMeterSquared; + return Math.Abs(AsBaseUnitNewtonSecondsPerMeterSquared() - other.AsBaseUnitNewtonSecondsPerMeterSquared()) <= maxError.AsBaseUnitNewtonSecondsPerMeterSquared(); } public override int GetHashCode() { - return _newtonSecondsPerMeterSquared.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -617,24 +584,24 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(DynamicViscosityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitNewtonSecondsPerMeterSquared(); + switch (unit) { - case DynamicViscosityUnit.Centipoise: - return Centipoise; - case DynamicViscosityUnit.MicropascalSecond: - return MicropascalSeconds; - case DynamicViscosityUnit.MillipascalSecond: - return MillipascalSeconds; - case DynamicViscosityUnit.NewtonSecondPerMeterSquared: - return NewtonSecondsPerMeterSquared; - case DynamicViscosityUnit.PascalSecond: - return PascalSeconds; - case DynamicViscosityUnit.Poise: - return Poise; + case DynamicViscosityUnit.Centipoise: return (baseUnitValue*10) / 1e-2d; + case DynamicViscosityUnit.MicropascalSecond: return (baseUnitValue) / 1e-6d; + case DynamicViscosityUnit.MillipascalSecond: return (baseUnitValue) / 1e-3d; + case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return baseUnitValue; + case DynamicViscosityUnit.PascalSecond: return baseUnitValue; + case DynamicViscosityUnit.Poise: return baseUnitValue*10; default: throw new NotImplementedException("unit: " + unit); @@ -676,7 +643,11 @@ public static DynamicViscosity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -695,17 +666,24 @@ public static DynamicViscosity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static DynamicViscosity Parse(string str, [CanBeNull] Culture culture) + public static DynamicViscosity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -731,16 +709,41 @@ public static bool TryParse([CanBeNull] string str, out DynamicViscosity result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out DynamicViscosity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out DynamicViscosity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -753,6 +756,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -766,11 +770,14 @@ public static DynamicViscosityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static DynamicViscosityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -779,6 +786,8 @@ public static DynamicViscosityUnit ParseUnit(string str, [CanBeNull] string cult /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -791,18 +800,18 @@ public static DynamicViscosityUnit ParseUnit(string str, [CanBeNull] string cult #else public #endif - static DynamicViscosityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static DynamicViscosityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == DynamicViscosityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized DynamicViscosityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -811,6 +820,7 @@ static DynamicViscosityUnit ParseUnit(string str, IFormatProvider formatProvider #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is NewtonSecondPerMeterSquared /// @@ -822,7 +832,7 @@ static DynamicViscosityUnit ParseUnit(string str, IFormatProvider formatProvider /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -839,74 +849,134 @@ public string ToString(DynamicViscosityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(DynamicViscosityUnit unit, [CanBeNull] Culture culture) + public string ToString( + DynamicViscosityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(DynamicViscosityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + DynamicViscosityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(DynamicViscosityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + DynamicViscosityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of DynamicViscosity /// - public static DynamicViscosity MaxValue - { - get - { - return new DynamicViscosity(double.MaxValue); - } - } + public static DynamicViscosity MaxValue => new DynamicViscosity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of DynamicViscosity /// - public static DynamicViscosity MinValue + public static DynamicViscosity MinValue => new DynamicViscosity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitNewtonSecondsPerMeterSquared() { - get + if (Unit == DynamicViscosityUnit.NewtonSecondPerMeterSquared) { return _value; } + + switch (Unit) { - return new DynamicViscosity(double.MinValue); - } - } - } + case DynamicViscosityUnit.Centipoise: return (_value/10) * 1e-2d; + case DynamicViscosityUnit.MicropascalSecond: return (_value) * 1e-6d; + case DynamicViscosityUnit.MillipascalSecond: return (_value) * 1e-3d; + case DynamicViscosityUnit.NewtonSecondPerMeterSquared: return _value; + case DynamicViscosityUnit.PascalSecond: return _value; + case DynamicViscosityUnit.Poise: return _value/10; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(DynamicViscosityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs index dc0d9902de..7061f96227 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricAdmittance : IComparable, IComparable - /// Base unit of ElectricAdmittance. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _siemens; + private readonly ElectricAdmittanceUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricAdmittance() : this(0) + public ElectricAdmittance() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricAdmittance(double siemens) { - _siemens = Convert.ToDouble(siemens); + _value = Convert.ToDouble(siemens); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricAdmittance(double numericValue, ElectricAdmittanceUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Siemens. + /// + /// Value assuming base unit Siemens. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricAdmittance(long siemens) - { - _siemens = Convert.ToDouble(siemens); - } + ElectricAdmittance(long siemens) : this(Convert.ToDouble(siemens), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Siemens. + /// + /// Value assuming base unit Siemens. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricAdmittance(decimal siemens) - { - _siemens = Convert.ToDouble(siemens); - } + ElectricAdmittance(decimal siemens) : this(Convert.ToDouble(siemens), BaseUnit) { } #region Properties @@ -119,56 +156,34 @@ public ElectricAdmittance(double siemens) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricAdmittanceUnit BaseUnit - { - get { return ElectricAdmittanceUnit.Siemens; } - } + public static ElectricAdmittanceUnit BaseUnit => ElectricAdmittanceUnit.Siemens; /// /// All units of measurement for the ElectricAdmittance quantity. /// public static ElectricAdmittanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().ToArray(); - /// /// Get ElectricAdmittance in Microsiemens. /// - public double Microsiemens - { - get { return (_siemens) / 1e-6d; } - } - + public double Microsiemens => As(ElectricAdmittanceUnit.Microsiemens); /// /// Get ElectricAdmittance in Millisiemens. /// - public double Millisiemens - { - get { return (_siemens) / 1e-3d; } - } - + public double Millisiemens => As(ElectricAdmittanceUnit.Millisiemens); /// /// Get ElectricAdmittance in Nanosiemens. /// - public double Nanosiemens - { - get { return (_siemens) / 1e-9d; } - } - + public double Nanosiemens => As(ElectricAdmittanceUnit.Nanosiemens); /// /// Get ElectricAdmittance in Siemens. /// - public double Siemens - { - get { return _siemens; } - } + public double Siemens => As(ElectricAdmittanceUnit.Siemens); #endregion #region Static - public static ElectricAdmittance Zero - { - get { return new ElectricAdmittance(); } - } + public static ElectricAdmittance Zero => new ElectricAdmittance(0, BaseUnit); /// /// Get ElectricAdmittance from Microsiemens. @@ -176,17 +191,13 @@ public static ElectricAdmittance Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricAdmittance FromMicrosiemens(double microsiemens) - { - double value = (double) microsiemens; - return new ElectricAdmittance((value) * 1e-6d); - } #else public static ElectricAdmittance FromMicrosiemens(QuantityValue microsiemens) +#endif { double value = (double) microsiemens; - return new ElectricAdmittance(((value) * 1e-6d)); + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); } -#endif /// /// Get ElectricAdmittance from Millisiemens. @@ -194,17 +205,13 @@ public static ElectricAdmittance FromMicrosiemens(QuantityValue microsiemens) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricAdmittance FromMillisiemens(double millisiemens) - { - double value = (double) millisiemens; - return new ElectricAdmittance((value) * 1e-3d); - } #else public static ElectricAdmittance FromMillisiemens(QuantityValue millisiemens) +#endif { double value = (double) millisiemens; - return new ElectricAdmittance(((value) * 1e-3d)); + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); } -#endif /// /// Get ElectricAdmittance from Nanosiemens. @@ -212,17 +219,13 @@ public static ElectricAdmittance FromMillisiemens(QuantityValue millisiemens) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricAdmittance FromNanosiemens(double nanosiemens) - { - double value = (double) nanosiemens; - return new ElectricAdmittance((value) * 1e-9d); - } #else public static ElectricAdmittance FromNanosiemens(QuantityValue nanosiemens) +#endif { double value = (double) nanosiemens; - return new ElectricAdmittance(((value) * 1e-9d)); + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); } -#endif /// /// Get ElectricAdmittance from Siemens. @@ -230,17 +233,13 @@ public static ElectricAdmittance FromNanosiemens(QuantityValue nanosiemens) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricAdmittance FromSiemens(double siemens) - { - double value = (double) siemens; - return new ElectricAdmittance(value); - } #else public static ElectricAdmittance FromSiemens(QuantityValue siemens) +#endif { double value = (double) siemens; - return new ElectricAdmittance((value)); + return new ElectricAdmittance(value, ElectricAdmittanceUnit.Siemens); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -320,20 +319,7 @@ public static ElectricAdmittance From(double value, ElectricAdmittanceUnit fromU public static ElectricAdmittance From(QuantityValue value, ElectricAdmittanceUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricAdmittanceUnit.Microsiemens: - return FromMicrosiemens(value); - case ElectricAdmittanceUnit.Millisiemens: - return FromMillisiemens(value); - case ElectricAdmittanceUnit.Nanosiemens: - return FromNanosiemens(value); - case ElectricAdmittanceUnit.Siemens: - return FromSiemens(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricAdmittance((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -350,20 +336,8 @@ public static ElectricAdmittance From(QuantityValue value, ElectricAdmittanceUni { return null; } - switch (fromUnit) - { - case ElectricAdmittanceUnit.Microsiemens: - return FromMicrosiemens(value.Value); - case ElectricAdmittanceUnit.Millisiemens: - return FromMillisiemens(value.Value); - case ElectricAdmittanceUnit.Nanosiemens: - return FromNanosiemens(value.Value); - case ElectricAdmittanceUnit.Siemens: - return FromSiemens(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricAdmittance((double)value.Value, fromUnit); } #endif @@ -382,12 +356,29 @@ public static string GetAbbreviation(ElectricAdmittanceUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricAdmittanceUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricAdmittanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -398,37 +389,37 @@ public static string GetAbbreviation(ElectricAdmittanceUnit unit, [CanBeNull] Cu #if !WINDOWS_UWP public static ElectricAdmittance operator -(ElectricAdmittance right) { - return new ElectricAdmittance(-right._siemens); + return new ElectricAdmittance(-right.Value, right.Unit); } public static ElectricAdmittance operator +(ElectricAdmittance left, ElectricAdmittance right) { - return new ElectricAdmittance(left._siemens + right._siemens); + return new ElectricAdmittance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricAdmittance operator -(ElectricAdmittance left, ElectricAdmittance right) { - return new ElectricAdmittance(left._siemens - right._siemens); + return new ElectricAdmittance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricAdmittance operator *(double left, ElectricAdmittance right) { - return new ElectricAdmittance(left*right._siemens); + return new ElectricAdmittance(left * right.Value, right.Unit); } public static ElectricAdmittance operator *(ElectricAdmittance left, double right) { - return new ElectricAdmittance(left._siemens*(double)right); + return new ElectricAdmittance(left.Value * right, left.Unit); } public static ElectricAdmittance operator /(ElectricAdmittance left, double right) { - return new ElectricAdmittance(left._siemens/(double)right); + return new ElectricAdmittance(left.Value / right, left.Unit); } public static double operator /(ElectricAdmittance left, ElectricAdmittance right) { - return Convert.ToDouble(left._siemens/right._siemens); + return left.Siemens / right.Siemens; } #endif @@ -451,43 +442,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricAdmittance other) { - return _siemens.CompareTo(other._siemens); + return AsBaseUnitSiemens().CompareTo(other.AsBaseUnitSiemens()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricAdmittance left, ElectricAdmittance right) { - return left._siemens <= right._siemens; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricAdmittance left, ElectricAdmittance right) { - return left._siemens >= right._siemens; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricAdmittance left, ElectricAdmittance right) { - return left._siemens < right._siemens; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricAdmittance left, ElectricAdmittance right) { - return left._siemens > right._siemens; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricAdmittance left, ElectricAdmittance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._siemens == right._siemens; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricAdmittance left, ElectricAdmittance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._siemens != right._siemens; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -499,7 +490,7 @@ public override bool Equals(object obj) return false; } - return _siemens.Equals(((ElectricAdmittance) obj)._siemens); + return AsBaseUnitSiemens().Equals(((ElectricAdmittance) obj).AsBaseUnitSiemens()); } /// @@ -512,12 +503,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricAdmittance other, ElectricAdmittance maxError) { - return Math.Abs(_siemens - other._siemens) <= maxError._siemens; + return Math.Abs(AsBaseUnitSiemens() - other.AsBaseUnitSiemens()) <= maxError.AsBaseUnitSiemens(); } public override int GetHashCode() { - return _siemens.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -527,20 +518,22 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricAdmittanceUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitSiemens(); + switch (unit) { - case ElectricAdmittanceUnit.Microsiemens: - return Microsiemens; - case ElectricAdmittanceUnit.Millisiemens: - return Millisiemens; - case ElectricAdmittanceUnit.Nanosiemens: - return Nanosiemens; - case ElectricAdmittanceUnit.Siemens: - return Siemens; + case ElectricAdmittanceUnit.Microsiemens: return (baseUnitValue) / 1e-6d; + case ElectricAdmittanceUnit.Millisiemens: return (baseUnitValue) / 1e-3d; + case ElectricAdmittanceUnit.Nanosiemens: return (baseUnitValue) / 1e-9d; + case ElectricAdmittanceUnit.Siemens: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -582,7 +575,11 @@ public static ElectricAdmittance Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -601,17 +598,24 @@ public static ElectricAdmittance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricAdmittance Parse(string str, [CanBeNull] Culture culture) + public static ElectricAdmittance Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -637,16 +641,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricAdmittance resul /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricAdmittance result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricAdmittance result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -659,6 +688,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -672,11 +702,14 @@ public static ElectricAdmittanceUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricAdmittanceUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -685,6 +718,8 @@ public static ElectricAdmittanceUnit ParseUnit(string str, [CanBeNull] string cu /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -697,18 +732,18 @@ public static ElectricAdmittanceUnit ParseUnit(string str, [CanBeNull] string cu #else public #endif - static ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricAdmittanceUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricAdmittanceUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -717,6 +752,7 @@ static ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider formatProvid #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Siemens /// @@ -728,7 +764,7 @@ static ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider formatProvid /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -745,74 +781,132 @@ public string ToString(ElectricAdmittanceUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricAdmittanceUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricAdmittanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricAdmittanceUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricAdmittanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricAdmittanceUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricAdmittanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricAdmittance /// - public static ElectricAdmittance MaxValue - { - get - { - return new ElectricAdmittance(double.MaxValue); - } - } + public static ElectricAdmittance MaxValue => new ElectricAdmittance(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricAdmittance /// - public static ElectricAdmittance MinValue + public static ElectricAdmittance MinValue => new ElectricAdmittance(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitSiemens() { - get + if (Unit == ElectricAdmittanceUnit.Siemens) { return _value; } + + switch (Unit) { - return new ElectricAdmittance(double.MinValue); - } - } - } + case ElectricAdmittanceUnit.Microsiemens: return (_value) * 1e-6d; + case ElectricAdmittanceUnit.Millisiemens: return (_value) * 1e-3d; + case ElectricAdmittanceUnit.Nanosiemens: return (_value) * 1e-9d; + case ElectricAdmittanceUnit.Siemens: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricAdmittanceUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs index 6e9120b0ee..27153d0e30 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricCharge : IComparable, IComparable #endif { /// - /// Base unit of ElectricCharge. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricChargeUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _coulombs; + public ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricCharge() : this(0) + public ElectricCharge() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricCharge(double coulombs) { - _coulombs = Convert.ToDouble(coulombs); + _value = Convert.ToDouble(coulombs); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricCharge(double numericValue, ElectricChargeUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Coulomb. + /// + /// Value assuming base unit Coulomb. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricCharge(long coulombs) - { - _coulombs = Convert.ToDouble(coulombs); - } + ElectricCharge(long coulombs) : this(Convert.ToDouble(coulombs), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Coulomb. + /// + /// Value assuming base unit Coulomb. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricCharge(decimal coulombs) - { - _coulombs = Convert.ToDouble(coulombs); - } + ElectricCharge(decimal coulombs) : this(Convert.ToDouble(coulombs), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public ElectricCharge(double coulombs) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricChargeUnit BaseUnit - { - get { return ElectricChargeUnit.Coulomb; } - } + public static ElectricChargeUnit BaseUnit => ElectricChargeUnit.Coulomb; /// /// All units of measurement for the ElectricCharge quantity. /// public static ElectricChargeUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().ToArray(); - /// /// Get ElectricCharge in Coulombs. /// - public double Coulombs - { - get { return _coulombs; } - } + public double Coulombs => As(ElectricChargeUnit.Coulomb); #endregion #region Static - public static ElectricCharge Zero - { - get { return new ElectricCharge(); } - } + public static ElectricCharge Zero => new ElectricCharge(0, BaseUnit); /// /// Get ElectricCharge from Coulombs. @@ -152,17 +179,13 @@ public static ElectricCharge Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricCharge FromCoulombs(double coulombs) - { - double value = (double) coulombs; - return new ElectricCharge(value); - } #else public static ElectricCharge FromCoulombs(QuantityValue coulombs) +#endif { double value = (double) coulombs; - return new ElectricCharge((value)); + return new ElectricCharge(value, ElectricChargeUnit.Coulomb); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static ElectricCharge From(double value, ElectricChargeUnit fromUnit) public static ElectricCharge From(QuantityValue value, ElectricChargeUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricChargeUnit.Coulomb: - return FromCoulombs(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricCharge((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static ElectricCharge From(QuantityValue value, ElectricChargeUnit fromUn { return null; } - switch (fromUnit) - { - case ElectricChargeUnit.Coulomb: - return FromCoulombs(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricCharge((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(ElectricChargeUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricChargeUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricChargeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(ElectricChargeUnit unit, [CanBeNull] Cultur #if !WINDOWS_UWP public static ElectricCharge operator -(ElectricCharge right) { - return new ElectricCharge(-right._coulombs); + return new ElectricCharge(-right.Value, right.Unit); } public static ElectricCharge operator +(ElectricCharge left, ElectricCharge right) { - return new ElectricCharge(left._coulombs + right._coulombs); + return new ElectricCharge(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricCharge operator -(ElectricCharge left, ElectricCharge right) { - return new ElectricCharge(left._coulombs - right._coulombs); + return new ElectricCharge(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricCharge operator *(double left, ElectricCharge right) { - return new ElectricCharge(left*right._coulombs); + return new ElectricCharge(left * right.Value, right.Unit); } public static ElectricCharge operator *(ElectricCharge left, double right) { - return new ElectricCharge(left._coulombs*(double)right); + return new ElectricCharge(left.Value * right, left.Unit); } public static ElectricCharge operator /(ElectricCharge left, double right) { - return new ElectricCharge(left._coulombs/(double)right); + return new ElectricCharge(left.Value / right, left.Unit); } public static double operator /(ElectricCharge left, ElectricCharge right) { - return Convert.ToDouble(left._coulombs/right._coulombs); + return left.Coulombs / right.Coulombs; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricCharge other) { - return _coulombs.CompareTo(other._coulombs); + return AsBaseUnitCoulombs().CompareTo(other.AsBaseUnitCoulombs()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricCharge left, ElectricCharge right) { - return left._coulombs <= right._coulombs; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricCharge left, ElectricCharge right) { - return left._coulombs >= right._coulombs; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricCharge left, ElectricCharge right) { - return left._coulombs < right._coulombs; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricCharge left, ElectricCharge right) { - return left._coulombs > right._coulombs; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricCharge left, ElectricCharge right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._coulombs == right._coulombs; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricCharge left, ElectricCharge right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._coulombs != right._coulombs; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _coulombs.Equals(((ElectricCharge) obj)._coulombs); + return AsBaseUnitCoulombs().Equals(((ElectricCharge) obj).AsBaseUnitCoulombs()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricCharge other, ElectricCharge maxError) { - return Math.Abs(_coulombs - other._coulombs) <= maxError._coulombs; + return Math.Abs(AsBaseUnitCoulombs() - other.AsBaseUnitCoulombs()) <= maxError.AsBaseUnitCoulombs(); } public override int GetHashCode() { - return _coulombs.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricChargeUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitCoulombs(); + switch (unit) { - case ElectricChargeUnit.Coulomb: - return Coulombs; + case ElectricChargeUnit.Coulomb: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static ElectricCharge Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static ElectricCharge Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricCharge Parse(string str, [CanBeNull] Culture culture) + public static ElectricCharge Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricCharge result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricCharge result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricCharge result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static ElectricChargeUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricChargeUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static ElectricChargeUnit ParseUnit(string str, [CanBeNull] string cultur /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static ElectricChargeUnit ParseUnit(string str, [CanBeNull] string cultur #else public #endif - static ElectricChargeUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricChargeUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricChargeUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricChargeUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static ElectricChargeUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Coulomb /// @@ -587,7 +662,7 @@ static ElectricChargeUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(ElectricChargeUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricChargeUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricChargeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricChargeUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricChargeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricChargeUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricChargeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricCharge /// - public static ElectricCharge MaxValue - { - get - { - return new ElectricCharge(double.MaxValue); - } - } + public static ElectricCharge MaxValue => new ElectricCharge(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricCharge /// - public static ElectricCharge MinValue + public static ElectricCharge MinValue => new ElectricCharge(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitCoulombs() { - get + if (Unit == ElectricChargeUnit.Coulomb) { return _value; } + + switch (Unit) { - return new ElectricCharge(double.MinValue); - } - } - } + case ElectricChargeUnit.Coulomb: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricChargeUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs index 9800700ef6..42da61e0a2 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricChargeDensity : IComparable, IComparable - /// Base unit of ElectricChargeDensity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricChargeDensityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _coulombsPerCubicMeter; + public ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricChargeDensity() : this(0) + public ElectricChargeDensity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricChargeDensity(double coulombspercubicmeter) { - _coulombsPerCubicMeter = Convert.ToDouble(coulombspercubicmeter); + _value = Convert.ToDouble(coulombspercubicmeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricChargeDensity(double numericValue, ElectricChargeDensityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit CoulombPerCubicMeter. + /// + /// Value assuming base unit CoulombPerCubicMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricChargeDensity(long coulombspercubicmeter) - { - _coulombsPerCubicMeter = Convert.ToDouble(coulombspercubicmeter); - } + ElectricChargeDensity(long coulombspercubicmeter) : this(Convert.ToDouble(coulombspercubicmeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit CoulombPerCubicMeter. + /// + /// Value assuming base unit CoulombPerCubicMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricChargeDensity(decimal coulombspercubicmeter) - { - _coulombsPerCubicMeter = Convert.ToDouble(coulombspercubicmeter); - } + ElectricChargeDensity(decimal coulombspercubicmeter) : this(Convert.ToDouble(coulombspercubicmeter), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public ElectricChargeDensity(double coulombspercubicmeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricChargeDensityUnit BaseUnit - { - get { return ElectricChargeDensityUnit.CoulombPerCubicMeter; } - } + public static ElectricChargeDensityUnit BaseUnit => ElectricChargeDensityUnit.CoulombPerCubicMeter; /// /// All units of measurement for the ElectricChargeDensity quantity. /// public static ElectricChargeDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().ToArray(); - /// /// Get ElectricChargeDensity in CoulombsPerCubicMeter. /// - public double CoulombsPerCubicMeter - { - get { return _coulombsPerCubicMeter; } - } + public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); #endregion #region Static - public static ElectricChargeDensity Zero - { - get { return new ElectricChargeDensity(); } - } + public static ElectricChargeDensity Zero => new ElectricChargeDensity(0, BaseUnit); /// /// Get ElectricChargeDensity from CoulombsPerCubicMeter. @@ -152,17 +179,13 @@ public static ElectricChargeDensity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricChargeDensity FromCoulombsPerCubicMeter(double coulombspercubicmeter) - { - double value = (double) coulombspercubicmeter; - return new ElectricChargeDensity(value); - } #else public static ElectricChargeDensity FromCoulombsPerCubicMeter(QuantityValue coulombspercubicmeter) +#endif { double value = (double) coulombspercubicmeter; - return new ElectricChargeDensity((value)); + return new ElectricChargeDensity(value, ElectricChargeDensityUnit.CoulombPerCubicMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static ElectricChargeDensity From(double value, ElectricChargeDensityUnit public static ElectricChargeDensity From(QuantityValue value, ElectricChargeDensityUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: - return FromCoulombsPerCubicMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricChargeDensity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static ElectricChargeDensity From(QuantityValue value, ElectricChargeDens { return null; } - switch (fromUnit) - { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: - return FromCoulombsPerCubicMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricChargeDensity((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(ElectricChargeDensityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricChargeDensityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricChargeDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(ElectricChargeDensityUnit unit, [CanBeNull] #if !WINDOWS_UWP public static ElectricChargeDensity operator -(ElectricChargeDensity right) { - return new ElectricChargeDensity(-right._coulombsPerCubicMeter); + return new ElectricChargeDensity(-right.Value, right.Unit); } public static ElectricChargeDensity operator +(ElectricChargeDensity left, ElectricChargeDensity right) { - return new ElectricChargeDensity(left._coulombsPerCubicMeter + right._coulombsPerCubicMeter); + return new ElectricChargeDensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricChargeDensity operator -(ElectricChargeDensity left, ElectricChargeDensity right) { - return new ElectricChargeDensity(left._coulombsPerCubicMeter - right._coulombsPerCubicMeter); + return new ElectricChargeDensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricChargeDensity operator *(double left, ElectricChargeDensity right) { - return new ElectricChargeDensity(left*right._coulombsPerCubicMeter); + return new ElectricChargeDensity(left * right.Value, right.Unit); } public static ElectricChargeDensity operator *(ElectricChargeDensity left, double right) { - return new ElectricChargeDensity(left._coulombsPerCubicMeter*(double)right); + return new ElectricChargeDensity(left.Value * right, left.Unit); } public static ElectricChargeDensity operator /(ElectricChargeDensity left, double right) { - return new ElectricChargeDensity(left._coulombsPerCubicMeter/(double)right); + return new ElectricChargeDensity(left.Value / right, left.Unit); } public static double operator /(ElectricChargeDensity left, ElectricChargeDensity right) { - return Convert.ToDouble(left._coulombsPerCubicMeter/right._coulombsPerCubicMeter); + return left.CoulombsPerCubicMeter / right.CoulombsPerCubicMeter; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricChargeDensity other) { - return _coulombsPerCubicMeter.CompareTo(other._coulombsPerCubicMeter); + return AsBaseUnitCoulombsPerCubicMeter().CompareTo(other.AsBaseUnitCoulombsPerCubicMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricChargeDensity left, ElectricChargeDensity right) { - return left._coulombsPerCubicMeter <= right._coulombsPerCubicMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricChargeDensity left, ElectricChargeDensity right) { - return left._coulombsPerCubicMeter >= right._coulombsPerCubicMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricChargeDensity left, ElectricChargeDensity right) { - return left._coulombsPerCubicMeter < right._coulombsPerCubicMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricChargeDensity left, ElectricChargeDensity right) { - return left._coulombsPerCubicMeter > right._coulombsPerCubicMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricChargeDensity left, ElectricChargeDensity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._coulombsPerCubicMeter == right._coulombsPerCubicMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricChargeDensity left, ElectricChargeDensity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._coulombsPerCubicMeter != right._coulombsPerCubicMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _coulombsPerCubicMeter.Equals(((ElectricChargeDensity) obj)._coulombsPerCubicMeter); + return AsBaseUnitCoulombsPerCubicMeter().Equals(((ElectricChargeDensity) obj).AsBaseUnitCoulombsPerCubicMeter()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricChargeDensity other, ElectricChargeDensity maxError) { - return Math.Abs(_coulombsPerCubicMeter - other._coulombsPerCubicMeter) <= maxError._coulombsPerCubicMeter; + return Math.Abs(AsBaseUnitCoulombsPerCubicMeter() - other.AsBaseUnitCoulombsPerCubicMeter()) <= maxError.AsBaseUnitCoulombsPerCubicMeter(); } public override int GetHashCode() { - return _coulombsPerCubicMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricChargeDensityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitCoulombsPerCubicMeter(); + switch (unit) { - case ElectricChargeDensityUnit.CoulombPerCubicMeter: - return CoulombsPerCubicMeter; + case ElectricChargeDensityUnit.CoulombPerCubicMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static ElectricChargeDensity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static ElectricChargeDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricChargeDensity Parse(string str, [CanBeNull] Culture culture) + public static ElectricChargeDensity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricChargeDensity re /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricChargeDensity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricChargeDensity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static ElectricChargeDensityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricChargeDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static ElectricChargeDensityUnit ParseUnit(string str, [CanBeNull] string /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static ElectricChargeDensityUnit ParseUnit(string str, [CanBeNull] string #else public #endif - static ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricChargeDensityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricChargeDensityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider formatPro #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is CoulombPerCubicMeter /// @@ -587,7 +662,7 @@ static ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider formatPro /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(ElectricChargeDensityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricChargeDensityUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricChargeDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricChargeDensityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricChargeDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricChargeDensityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricChargeDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricChargeDensity /// - public static ElectricChargeDensity MaxValue - { - get - { - return new ElectricChargeDensity(double.MaxValue); - } - } + public static ElectricChargeDensity MaxValue => new ElectricChargeDensity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricChargeDensity /// - public static ElectricChargeDensity MinValue + public static ElectricChargeDensity MinValue => new ElectricChargeDensity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitCoulombsPerCubicMeter() { - get + if (Unit == ElectricChargeDensityUnit.CoulombPerCubicMeter) { return _value; } + + switch (Unit) { - return new ElectricChargeDensity(double.MinValue); - } - } - } + case ElectricChargeDensityUnit.CoulombPerCubicMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricChargeDensityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs index 8dd70e0693..301d90de7a 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricConductance : IComparable, IComparable - /// Base unit of ElectricConductance. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricConductanceUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _siemens; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricConductance() : this(0) + public ElectricConductance() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricConductance(double siemens) { - _siemens = Convert.ToDouble(siemens); + _value = Convert.ToDouble(siemens); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricConductance(double numericValue, ElectricConductanceUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Siemens. + /// + /// Value assuming base unit Siemens. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricConductance(long siemens) - { - _siemens = Convert.ToDouble(siemens); - } + ElectricConductance(long siemens) : this(Convert.ToDouble(siemens), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Siemens. + /// + /// Value assuming base unit Siemens. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricConductance(decimal siemens) - { - _siemens = Convert.ToDouble(siemens); - } + ElectricConductance(decimal siemens) : this(Convert.ToDouble(siemens), BaseUnit) { } #region Properties @@ -119,48 +156,30 @@ public ElectricConductance(double siemens) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricConductanceUnit BaseUnit - { - get { return ElectricConductanceUnit.Siemens; } - } + public static ElectricConductanceUnit BaseUnit => ElectricConductanceUnit.Siemens; /// /// All units of measurement for the ElectricConductance quantity. /// public static ElectricConductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().ToArray(); - /// /// Get ElectricConductance in Microsiemens. /// - public double Microsiemens - { - get { return (_siemens) / 1e-6d; } - } - + public double Microsiemens => As(ElectricConductanceUnit.Microsiemens); /// /// Get ElectricConductance in Millisiemens. /// - public double Millisiemens - { - get { return (_siemens) / 1e-3d; } - } - + public double Millisiemens => As(ElectricConductanceUnit.Millisiemens); /// /// Get ElectricConductance in Siemens. /// - public double Siemens - { - get { return _siemens; } - } + public double Siemens => As(ElectricConductanceUnit.Siemens); #endregion #region Static - public static ElectricConductance Zero - { - get { return new ElectricConductance(); } - } + public static ElectricConductance Zero => new ElectricConductance(0, BaseUnit); /// /// Get ElectricConductance from Microsiemens. @@ -168,17 +187,13 @@ public static ElectricConductance Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricConductance FromMicrosiemens(double microsiemens) - { - double value = (double) microsiemens; - return new ElectricConductance((value) * 1e-6d); - } #else public static ElectricConductance FromMicrosiemens(QuantityValue microsiemens) +#endif { double value = (double) microsiemens; - return new ElectricConductance(((value) * 1e-6d)); + return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); } -#endif /// /// Get ElectricConductance from Millisiemens. @@ -186,17 +201,13 @@ public static ElectricConductance FromMicrosiemens(QuantityValue microsiemens) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricConductance FromMillisiemens(double millisiemens) - { - double value = (double) millisiemens; - return new ElectricConductance((value) * 1e-3d); - } #else public static ElectricConductance FromMillisiemens(QuantityValue millisiemens) +#endif { double value = (double) millisiemens; - return new ElectricConductance(((value) * 1e-3d)); + return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); } -#endif /// /// Get ElectricConductance from Siemens. @@ -204,17 +215,13 @@ public static ElectricConductance FromMillisiemens(QuantityValue millisiemens) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricConductance FromSiemens(double siemens) - { - double value = (double) siemens; - return new ElectricConductance(value); - } #else public static ElectricConductance FromSiemens(QuantityValue siemens) +#endif { double value = (double) siemens; - return new ElectricConductance((value)); + return new ElectricConductance(value, ElectricConductanceUnit.Siemens); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -279,18 +286,7 @@ public static ElectricConductance From(double value, ElectricConductanceUnit fro public static ElectricConductance From(QuantityValue value, ElectricConductanceUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricConductanceUnit.Microsiemens: - return FromMicrosiemens(value); - case ElectricConductanceUnit.Millisiemens: - return FromMillisiemens(value); - case ElectricConductanceUnit.Siemens: - return FromSiemens(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricConductance((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -307,18 +303,8 @@ public static ElectricConductance From(QuantityValue value, ElectricConductanceU { return null; } - switch (fromUnit) - { - case ElectricConductanceUnit.Microsiemens: - return FromMicrosiemens(value.Value); - case ElectricConductanceUnit.Millisiemens: - return FromMillisiemens(value.Value); - case ElectricConductanceUnit.Siemens: - return FromSiemens(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricConductance((double)value.Value, fromUnit); } #endif @@ -337,12 +323,29 @@ public static string GetAbbreviation(ElectricConductanceUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricConductanceUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricConductanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -353,37 +356,37 @@ public static string GetAbbreviation(ElectricConductanceUnit unit, [CanBeNull] C #if !WINDOWS_UWP public static ElectricConductance operator -(ElectricConductance right) { - return new ElectricConductance(-right._siemens); + return new ElectricConductance(-right.Value, right.Unit); } public static ElectricConductance operator +(ElectricConductance left, ElectricConductance right) { - return new ElectricConductance(left._siemens + right._siemens); + return new ElectricConductance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricConductance operator -(ElectricConductance left, ElectricConductance right) { - return new ElectricConductance(left._siemens - right._siemens); + return new ElectricConductance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricConductance operator *(double left, ElectricConductance right) { - return new ElectricConductance(left*right._siemens); + return new ElectricConductance(left * right.Value, right.Unit); } public static ElectricConductance operator *(ElectricConductance left, double right) { - return new ElectricConductance(left._siemens*(double)right); + return new ElectricConductance(left.Value * right, left.Unit); } public static ElectricConductance operator /(ElectricConductance left, double right) { - return new ElectricConductance(left._siemens/(double)right); + return new ElectricConductance(left.Value / right, left.Unit); } public static double operator /(ElectricConductance left, ElectricConductance right) { - return Convert.ToDouble(left._siemens/right._siemens); + return left.Siemens / right.Siemens; } #endif @@ -406,43 +409,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricConductance other) { - return _siemens.CompareTo(other._siemens); + return AsBaseUnitSiemens().CompareTo(other.AsBaseUnitSiemens()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricConductance left, ElectricConductance right) { - return left._siemens <= right._siemens; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricConductance left, ElectricConductance right) { - return left._siemens >= right._siemens; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricConductance left, ElectricConductance right) { - return left._siemens < right._siemens; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricConductance left, ElectricConductance right) { - return left._siemens > right._siemens; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricConductance left, ElectricConductance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._siemens == right._siemens; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricConductance left, ElectricConductance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._siemens != right._siemens; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -454,7 +457,7 @@ public override bool Equals(object obj) return false; } - return _siemens.Equals(((ElectricConductance) obj)._siemens); + return AsBaseUnitSiemens().Equals(((ElectricConductance) obj).AsBaseUnitSiemens()); } /// @@ -467,12 +470,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricConductance other, ElectricConductance maxError) { - return Math.Abs(_siemens - other._siemens) <= maxError._siemens; + return Math.Abs(AsBaseUnitSiemens() - other.AsBaseUnitSiemens()) <= maxError.AsBaseUnitSiemens(); } public override int GetHashCode() { - return _siemens.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -482,18 +485,21 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricConductanceUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitSiemens(); + switch (unit) { - case ElectricConductanceUnit.Microsiemens: - return Microsiemens; - case ElectricConductanceUnit.Millisiemens: - return Millisiemens; - case ElectricConductanceUnit.Siemens: - return Siemens; + case ElectricConductanceUnit.Microsiemens: return (baseUnitValue) / 1e-6d; + case ElectricConductanceUnit.Millisiemens: return (baseUnitValue) / 1e-3d; + case ElectricConductanceUnit.Siemens: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -535,7 +541,11 @@ public static ElectricConductance Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -554,17 +564,24 @@ public static ElectricConductance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricConductance Parse(string str, [CanBeNull] Culture culture) + public static ElectricConductance Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -590,16 +607,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricConductance resu /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricConductance result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricConductance result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -612,6 +654,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -625,11 +668,14 @@ public static ElectricConductanceUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricConductanceUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -638,6 +684,8 @@ public static ElectricConductanceUnit ParseUnit(string str, [CanBeNull] string c /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -650,18 +698,18 @@ public static ElectricConductanceUnit ParseUnit(string str, [CanBeNull] string c #else public #endif - static ElectricConductanceUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricConductanceUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricConductanceUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricConductanceUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -670,6 +718,7 @@ static ElectricConductanceUnit ParseUnit(string str, IFormatProvider formatProvi #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Siemens /// @@ -681,7 +730,7 @@ static ElectricConductanceUnit ParseUnit(string str, IFormatProvider formatProvi /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -698,74 +747,131 @@ public string ToString(ElectricConductanceUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricConductanceUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricConductanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricConductanceUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricConductanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricConductanceUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricConductanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricConductance /// - public static ElectricConductance MaxValue - { - get - { - return new ElectricConductance(double.MaxValue); - } - } + public static ElectricConductance MaxValue => new ElectricConductance(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricConductance /// - public static ElectricConductance MinValue + public static ElectricConductance MinValue => new ElectricConductance(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitSiemens() { - get + if (Unit == ElectricConductanceUnit.Siemens) { return _value; } + + switch (Unit) { - return new ElectricConductance(double.MinValue); - } - } - } + case ElectricConductanceUnit.Microsiemens: return (_value) * 1e-6d; + case ElectricConductanceUnit.Millisiemens: return (_value) * 1e-3d; + case ElectricConductanceUnit.Siemens: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricConductanceUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs index e695c63f35..6e86f77bfc 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricConductivity : IComparable, IComparable - /// Base unit of ElectricConductivity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricConductivityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _siemensPerMeter; + public ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricConductivity() : this(0) + public ElectricConductivity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricConductivity(double siemenspermeter) { - _siemensPerMeter = Convert.ToDouble(siemenspermeter); + _value = Convert.ToDouble(siemenspermeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricConductivity(double numericValue, ElectricConductivityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit SiemensPerMeter. + /// + /// Value assuming base unit SiemensPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricConductivity(long siemenspermeter) - { - _siemensPerMeter = Convert.ToDouble(siemenspermeter); - } + ElectricConductivity(long siemenspermeter) : this(Convert.ToDouble(siemenspermeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit SiemensPerMeter. + /// + /// Value assuming base unit SiemensPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricConductivity(decimal siemenspermeter) - { - _siemensPerMeter = Convert.ToDouble(siemenspermeter); - } + ElectricConductivity(decimal siemenspermeter) : this(Convert.ToDouble(siemenspermeter), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public ElectricConductivity(double siemenspermeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricConductivityUnit BaseUnit - { - get { return ElectricConductivityUnit.SiemensPerMeter; } - } + public static ElectricConductivityUnit BaseUnit => ElectricConductivityUnit.SiemensPerMeter; /// /// All units of measurement for the ElectricConductivity quantity. /// public static ElectricConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().ToArray(); - /// /// Get ElectricConductivity in SiemensPerMeter. /// - public double SiemensPerMeter - { - get { return _siemensPerMeter; } - } + public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); #endregion #region Static - public static ElectricConductivity Zero - { - get { return new ElectricConductivity(); } - } + public static ElectricConductivity Zero => new ElectricConductivity(0, BaseUnit); /// /// Get ElectricConductivity from SiemensPerMeter. @@ -152,17 +179,13 @@ public static ElectricConductivity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricConductivity FromSiemensPerMeter(double siemenspermeter) - { - double value = (double) siemenspermeter; - return new ElectricConductivity(value); - } #else public static ElectricConductivity FromSiemensPerMeter(QuantityValue siemenspermeter) +#endif { double value = (double) siemenspermeter; - return new ElectricConductivity((value)); + return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static ElectricConductivity From(double value, ElectricConductivityUnit f public static ElectricConductivity From(QuantityValue value, ElectricConductivityUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricConductivityUnit.SiemensPerMeter: - return FromSiemensPerMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricConductivity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static ElectricConductivity From(QuantityValue value, ElectricConductivit { return null; } - switch (fromUnit) - { - case ElectricConductivityUnit.SiemensPerMeter: - return FromSiemensPerMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricConductivity((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(ElectricConductivityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricConductivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(ElectricConductivityUnit unit, [CanBeNull] #if !WINDOWS_UWP public static ElectricConductivity operator -(ElectricConductivity right) { - return new ElectricConductivity(-right._siemensPerMeter); + return new ElectricConductivity(-right.Value, right.Unit); } public static ElectricConductivity operator +(ElectricConductivity left, ElectricConductivity right) { - return new ElectricConductivity(left._siemensPerMeter + right._siemensPerMeter); + return new ElectricConductivity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricConductivity operator -(ElectricConductivity left, ElectricConductivity right) { - return new ElectricConductivity(left._siemensPerMeter - right._siemensPerMeter); + return new ElectricConductivity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricConductivity operator *(double left, ElectricConductivity right) { - return new ElectricConductivity(left*right._siemensPerMeter); + return new ElectricConductivity(left * right.Value, right.Unit); } public static ElectricConductivity operator *(ElectricConductivity left, double right) { - return new ElectricConductivity(left._siemensPerMeter*(double)right); + return new ElectricConductivity(left.Value * right, left.Unit); } public static ElectricConductivity operator /(ElectricConductivity left, double right) { - return new ElectricConductivity(left._siemensPerMeter/(double)right); + return new ElectricConductivity(left.Value / right, left.Unit); } public static double operator /(ElectricConductivity left, ElectricConductivity right) { - return Convert.ToDouble(left._siemensPerMeter/right._siemensPerMeter); + return left.SiemensPerMeter / right.SiemensPerMeter; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricConductivity other) { - return _siemensPerMeter.CompareTo(other._siemensPerMeter); + return AsBaseUnitSiemensPerMeter().CompareTo(other.AsBaseUnitSiemensPerMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricConductivity left, ElectricConductivity right) { - return left._siemensPerMeter <= right._siemensPerMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricConductivity left, ElectricConductivity right) { - return left._siemensPerMeter >= right._siemensPerMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricConductivity left, ElectricConductivity right) { - return left._siemensPerMeter < right._siemensPerMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricConductivity left, ElectricConductivity right) { - return left._siemensPerMeter > right._siemensPerMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricConductivity left, ElectricConductivity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._siemensPerMeter == right._siemensPerMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricConductivity left, ElectricConductivity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._siemensPerMeter != right._siemensPerMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _siemensPerMeter.Equals(((ElectricConductivity) obj)._siemensPerMeter); + return AsBaseUnitSiemensPerMeter().Equals(((ElectricConductivity) obj).AsBaseUnitSiemensPerMeter()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricConductivity other, ElectricConductivity maxError) { - return Math.Abs(_siemensPerMeter - other._siemensPerMeter) <= maxError._siemensPerMeter; + return Math.Abs(AsBaseUnitSiemensPerMeter() - other.AsBaseUnitSiemensPerMeter()) <= maxError.AsBaseUnitSiemensPerMeter(); } public override int GetHashCode() { - return _siemensPerMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricConductivityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitSiemensPerMeter(); + switch (unit) { - case ElectricConductivityUnit.SiemensPerMeter: - return SiemensPerMeter; + case ElectricConductivityUnit.SiemensPerMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static ElectricConductivity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static ElectricConductivity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricConductivity Parse(string str, [CanBeNull] Culture culture) + public static ElectricConductivity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricConductivity res /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricConductivity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricConductivity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static ElectricConductivityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricConductivityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static ElectricConductivityUnit ParseUnit(string str, [CanBeNull] string /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static ElectricConductivityUnit ParseUnit(string str, [CanBeNull] string #else public #endif - static ElectricConductivityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricConductivityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricConductivityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricConductivityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static ElectricConductivityUnit ParseUnit(string str, IFormatProvider formatProv #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is SiemensPerMeter /// @@ -587,7 +662,7 @@ static ElectricConductivityUnit ParseUnit(string str, IFormatProvider formatProv /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(ElectricConductivityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricConductivityUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricConductivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricConductivityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricConductivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricConductivityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricConductivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricConductivity /// - public static ElectricConductivity MaxValue - { - get - { - return new ElectricConductivity(double.MaxValue); - } - } + public static ElectricConductivity MaxValue => new ElectricConductivity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricConductivity /// - public static ElectricConductivity MinValue + public static ElectricConductivity MinValue => new ElectricConductivity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitSiemensPerMeter() { - get + if (Unit == ElectricConductivityUnit.SiemensPerMeter) { return _value; } + + switch (Unit) { - return new ElectricConductivity(double.MinValue); - } - } - } + case ElectricConductivityUnit.SiemensPerMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricConductivityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs index ee2cdd0550..9262cef87a 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricCurrent : IComparable, IComparable - /// Base unit of ElectricCurrent. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _amperes; + public ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricCurrent() : this(0) + public ElectricCurrent() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricCurrent(double amperes) { - _amperes = Convert.ToDouble(amperes); + _value = Convert.ToDouble(amperes); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricCurrent(double numericValue, ElectricCurrentUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Ampere. + /// + /// Value assuming base unit Ampere. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricCurrent(long amperes) - { - _amperes = Convert.ToDouble(amperes); - } + ElectricCurrent(long amperes) : this(Convert.ToDouble(amperes), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Ampere. + /// + /// Value assuming base unit Ampere. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricCurrent(decimal amperes) - { - _amperes = Convert.ToDouble(amperes); - } + ElectricCurrent(decimal amperes) : this(Convert.ToDouble(amperes), BaseUnit) { } #region Properties @@ -119,80 +156,46 @@ public ElectricCurrent(double amperes) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricCurrentUnit BaseUnit - { - get { return ElectricCurrentUnit.Ampere; } - } + public static ElectricCurrentUnit BaseUnit => ElectricCurrentUnit.Ampere; /// /// All units of measurement for the ElectricCurrent quantity. /// public static ElectricCurrentUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().ToArray(); - /// /// Get ElectricCurrent in Amperes. /// - public double Amperes - { - get { return _amperes; } - } - + public double Amperes => As(ElectricCurrentUnit.Ampere); /// /// Get ElectricCurrent in Kiloamperes. /// - public double Kiloamperes - { - get { return (_amperes) / 1e3d; } - } - + public double Kiloamperes => As(ElectricCurrentUnit.Kiloampere); /// /// Get ElectricCurrent in Megaamperes. /// - public double Megaamperes - { - get { return (_amperes) / 1e6d; } - } - + public double Megaamperes => As(ElectricCurrentUnit.Megaampere); /// /// Get ElectricCurrent in Microamperes. /// - public double Microamperes - { - get { return (_amperes) / 1e-6d; } - } - + public double Microamperes => As(ElectricCurrentUnit.Microampere); /// /// Get ElectricCurrent in Milliamperes. /// - public double Milliamperes - { - get { return (_amperes) / 1e-3d; } - } - + public double Milliamperes => As(ElectricCurrentUnit.Milliampere); /// /// Get ElectricCurrent in Nanoamperes. /// - public double Nanoamperes - { - get { return (_amperes) / 1e-9d; } - } - + public double Nanoamperes => As(ElectricCurrentUnit.Nanoampere); /// /// Get ElectricCurrent in Picoamperes. /// - public double Picoamperes - { - get { return (_amperes) / 1e-12d; } - } + public double Picoamperes => As(ElectricCurrentUnit.Picoampere); #endregion #region Static - public static ElectricCurrent Zero - { - get { return new ElectricCurrent(); } - } + public static ElectricCurrent Zero => new ElectricCurrent(0, BaseUnit); /// /// Get ElectricCurrent from Amperes. @@ -200,17 +203,13 @@ public static ElectricCurrent Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricCurrent FromAmperes(double amperes) - { - double value = (double) amperes; - return new ElectricCurrent(value); - } #else public static ElectricCurrent FromAmperes(QuantityValue amperes) +#endif { double value = (double) amperes; - return new ElectricCurrent((value)); + return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); } -#endif /// /// Get ElectricCurrent from Kiloamperes. @@ -218,17 +217,13 @@ public static ElectricCurrent FromAmperes(QuantityValue amperes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricCurrent FromKiloamperes(double kiloamperes) - { - double value = (double) kiloamperes; - return new ElectricCurrent((value) * 1e3d); - } #else public static ElectricCurrent FromKiloamperes(QuantityValue kiloamperes) +#endif { double value = (double) kiloamperes; - return new ElectricCurrent(((value) * 1e3d)); + return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); } -#endif /// /// Get ElectricCurrent from Megaamperes. @@ -236,17 +231,13 @@ public static ElectricCurrent FromKiloamperes(QuantityValue kiloamperes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricCurrent FromMegaamperes(double megaamperes) - { - double value = (double) megaamperes; - return new ElectricCurrent((value) * 1e6d); - } #else public static ElectricCurrent FromMegaamperes(QuantityValue megaamperes) +#endif { double value = (double) megaamperes; - return new ElectricCurrent(((value) * 1e6d)); + return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); } -#endif /// /// Get ElectricCurrent from Microamperes. @@ -254,17 +245,13 @@ public static ElectricCurrent FromMegaamperes(QuantityValue megaamperes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricCurrent FromMicroamperes(double microamperes) - { - double value = (double) microamperes; - return new ElectricCurrent((value) * 1e-6d); - } #else public static ElectricCurrent FromMicroamperes(QuantityValue microamperes) +#endif { double value = (double) microamperes; - return new ElectricCurrent(((value) * 1e-6d)); + return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); } -#endif /// /// Get ElectricCurrent from Milliamperes. @@ -272,17 +259,13 @@ public static ElectricCurrent FromMicroamperes(QuantityValue microamperes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricCurrent FromMilliamperes(double milliamperes) - { - double value = (double) milliamperes; - return new ElectricCurrent((value) * 1e-3d); - } #else public static ElectricCurrent FromMilliamperes(QuantityValue milliamperes) +#endif { double value = (double) milliamperes; - return new ElectricCurrent(((value) * 1e-3d)); + return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); } -#endif /// /// Get ElectricCurrent from Nanoamperes. @@ -290,17 +273,13 @@ public static ElectricCurrent FromMilliamperes(QuantityValue milliamperes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricCurrent FromNanoamperes(double nanoamperes) - { - double value = (double) nanoamperes; - return new ElectricCurrent((value) * 1e-9d); - } #else public static ElectricCurrent FromNanoamperes(QuantityValue nanoamperes) +#endif { double value = (double) nanoamperes; - return new ElectricCurrent(((value) * 1e-9d)); + return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); } -#endif /// /// Get ElectricCurrent from Picoamperes. @@ -308,17 +287,13 @@ public static ElectricCurrent FromNanoamperes(QuantityValue nanoamperes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricCurrent FromPicoamperes(double picoamperes) - { - double value = (double) picoamperes; - return new ElectricCurrent((value) * 1e-12d); - } #else public static ElectricCurrent FromPicoamperes(QuantityValue picoamperes) +#endif { double value = (double) picoamperes; - return new ElectricCurrent(((value) * 1e-12d)); + return new ElectricCurrent(value, ElectricCurrentUnit.Picoampere); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -443,26 +418,7 @@ public static ElectricCurrent From(double value, ElectricCurrentUnit fromUnit) public static ElectricCurrent From(QuantityValue value, ElectricCurrentUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricCurrentUnit.Ampere: - return FromAmperes(value); - case ElectricCurrentUnit.Kiloampere: - return FromKiloamperes(value); - case ElectricCurrentUnit.Megaampere: - return FromMegaamperes(value); - case ElectricCurrentUnit.Microampere: - return FromMicroamperes(value); - case ElectricCurrentUnit.Milliampere: - return FromMilliamperes(value); - case ElectricCurrentUnit.Nanoampere: - return FromNanoamperes(value); - case ElectricCurrentUnit.Picoampere: - return FromPicoamperes(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricCurrent((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -479,26 +435,8 @@ public static ElectricCurrent From(QuantityValue value, ElectricCurrentUnit from { return null; } - switch (fromUnit) - { - case ElectricCurrentUnit.Ampere: - return FromAmperes(value.Value); - case ElectricCurrentUnit.Kiloampere: - return FromKiloamperes(value.Value); - case ElectricCurrentUnit.Megaampere: - return FromMegaamperes(value.Value); - case ElectricCurrentUnit.Microampere: - return FromMicroamperes(value.Value); - case ElectricCurrentUnit.Milliampere: - return FromMilliamperes(value.Value); - case ElectricCurrentUnit.Nanoampere: - return FromNanoamperes(value.Value); - case ElectricCurrentUnit.Picoampere: - return FromPicoamperes(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricCurrent((double)value.Value, fromUnit); } #endif @@ -517,12 +455,29 @@ public static string GetAbbreviation(ElectricCurrentUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricCurrentUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -533,37 +488,37 @@ public static string GetAbbreviation(ElectricCurrentUnit unit, [CanBeNull] Cultu #if !WINDOWS_UWP public static ElectricCurrent operator -(ElectricCurrent right) { - return new ElectricCurrent(-right._amperes); + return new ElectricCurrent(-right.Value, right.Unit); } public static ElectricCurrent operator +(ElectricCurrent left, ElectricCurrent right) { - return new ElectricCurrent(left._amperes + right._amperes); + return new ElectricCurrent(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricCurrent operator -(ElectricCurrent left, ElectricCurrent right) { - return new ElectricCurrent(left._amperes - right._amperes); + return new ElectricCurrent(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricCurrent operator *(double left, ElectricCurrent right) { - return new ElectricCurrent(left*right._amperes); + return new ElectricCurrent(left * right.Value, right.Unit); } public static ElectricCurrent operator *(ElectricCurrent left, double right) { - return new ElectricCurrent(left._amperes*(double)right); + return new ElectricCurrent(left.Value * right, left.Unit); } public static ElectricCurrent operator /(ElectricCurrent left, double right) { - return new ElectricCurrent(left._amperes/(double)right); + return new ElectricCurrent(left.Value / right, left.Unit); } public static double operator /(ElectricCurrent left, ElectricCurrent right) { - return Convert.ToDouble(left._amperes/right._amperes); + return left.Amperes / right.Amperes; } #endif @@ -586,43 +541,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricCurrent other) { - return _amperes.CompareTo(other._amperes); + return AsBaseUnitAmperes().CompareTo(other.AsBaseUnitAmperes()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricCurrent left, ElectricCurrent right) { - return left._amperes <= right._amperes; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricCurrent left, ElectricCurrent right) { - return left._amperes >= right._amperes; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricCurrent left, ElectricCurrent right) { - return left._amperes < right._amperes; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricCurrent left, ElectricCurrent right) { - return left._amperes > right._amperes; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricCurrent left, ElectricCurrent right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._amperes == right._amperes; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricCurrent left, ElectricCurrent right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._amperes != right._amperes; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -634,7 +589,7 @@ public override bool Equals(object obj) return false; } - return _amperes.Equals(((ElectricCurrent) obj)._amperes); + return AsBaseUnitAmperes().Equals(((ElectricCurrent) obj).AsBaseUnitAmperes()); } /// @@ -647,12 +602,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricCurrent other, ElectricCurrent maxError) { - return Math.Abs(_amperes - other._amperes) <= maxError._amperes; + return Math.Abs(AsBaseUnitAmperes() - other.AsBaseUnitAmperes()) <= maxError.AsBaseUnitAmperes(); } public override int GetHashCode() { - return _amperes.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -662,26 +617,25 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricCurrentUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitAmperes(); + switch (unit) { - case ElectricCurrentUnit.Ampere: - return Amperes; - case ElectricCurrentUnit.Kiloampere: - return Kiloamperes; - case ElectricCurrentUnit.Megaampere: - return Megaamperes; - case ElectricCurrentUnit.Microampere: - return Microamperes; - case ElectricCurrentUnit.Milliampere: - return Milliamperes; - case ElectricCurrentUnit.Nanoampere: - return Nanoamperes; - case ElectricCurrentUnit.Picoampere: - return Picoamperes; + case ElectricCurrentUnit.Ampere: return baseUnitValue; + case ElectricCurrentUnit.Kiloampere: return (baseUnitValue) / 1e3d; + case ElectricCurrentUnit.Megaampere: return (baseUnitValue) / 1e6d; + case ElectricCurrentUnit.Microampere: return (baseUnitValue) / 1e-6d; + case ElectricCurrentUnit.Milliampere: return (baseUnitValue) / 1e-3d; + case ElectricCurrentUnit.Nanoampere: return (baseUnitValue) / 1e-9d; + case ElectricCurrentUnit.Picoampere: return (baseUnitValue) / 1e-12d; default: throw new NotImplementedException("unit: " + unit); @@ -723,7 +677,11 @@ public static ElectricCurrent Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -742,17 +700,24 @@ public static ElectricCurrent Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricCurrent Parse(string str, [CanBeNull] Culture culture) + public static ElectricCurrent Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -778,16 +743,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricCurrent result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricCurrent result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricCurrent result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -800,6 +790,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -813,11 +804,14 @@ public static ElectricCurrentUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricCurrentUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -826,6 +820,8 @@ public static ElectricCurrentUnit ParseUnit(string str, [CanBeNull] string cultu /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -838,18 +834,18 @@ public static ElectricCurrentUnit ParseUnit(string str, [CanBeNull] string cultu #else public #endif - static ElectricCurrentUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricCurrentUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricCurrentUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -858,6 +854,7 @@ static ElectricCurrentUnit ParseUnit(string str, IFormatProvider formatProvider #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Ampere /// @@ -869,7 +866,7 @@ static ElectricCurrentUnit ParseUnit(string str, IFormatProvider formatProvider /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -886,74 +883,135 @@ public string ToString(ElectricCurrentUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricCurrentUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricCurrentUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricCurrentUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricCurrentUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricCurrentUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricCurrentUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricCurrent /// - public static ElectricCurrent MaxValue - { - get - { - return new ElectricCurrent(double.MaxValue); - } - } + public static ElectricCurrent MaxValue => new ElectricCurrent(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricCurrent /// - public static ElectricCurrent MinValue + public static ElectricCurrent MinValue => new ElectricCurrent(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitAmperes() { - get + if (Unit == ElectricCurrentUnit.Ampere) { return _value; } + + switch (Unit) { - return new ElectricCurrent(double.MinValue); - } - } - } + case ElectricCurrentUnit.Ampere: return _value; + case ElectricCurrentUnit.Kiloampere: return (_value) * 1e3d; + case ElectricCurrentUnit.Megaampere: return (_value) * 1e6d; + case ElectricCurrentUnit.Microampere: return (_value) * 1e-6d; + case ElectricCurrentUnit.Milliampere: return (_value) * 1e-3d; + case ElectricCurrentUnit.Nanoampere: return (_value) * 1e-9d; + case ElectricCurrentUnit.Picoampere: return (_value) * 1e-12d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricCurrentUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs index 614396c5d1..7c3d1d9318 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricCurrentDensity : IComparable, IComparable - /// Base unit of ElectricCurrentDensity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentDensityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _amperesPerSquareMeter; + public ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricCurrentDensity() : this(0) + public ElectricCurrentDensity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricCurrentDensity(double amperespersquaremeter) { - _amperesPerSquareMeter = Convert.ToDouble(amperespersquaremeter); + _value = Convert.ToDouble(amperespersquaremeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricCurrentDensity(double numericValue, ElectricCurrentDensityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit AmperePerSquareMeter. + /// + /// Value assuming base unit AmperePerSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricCurrentDensity(long amperespersquaremeter) - { - _amperesPerSquareMeter = Convert.ToDouble(amperespersquaremeter); - } + ElectricCurrentDensity(long amperespersquaremeter) : this(Convert.ToDouble(amperespersquaremeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit AmperePerSquareMeter. + /// + /// Value assuming base unit AmperePerSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricCurrentDensity(decimal amperespersquaremeter) - { - _amperesPerSquareMeter = Convert.ToDouble(amperespersquaremeter); - } + ElectricCurrentDensity(decimal amperespersquaremeter) : this(Convert.ToDouble(amperespersquaremeter), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public ElectricCurrentDensity(double amperespersquaremeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricCurrentDensityUnit BaseUnit - { - get { return ElectricCurrentDensityUnit.AmperePerSquareMeter; } - } + public static ElectricCurrentDensityUnit BaseUnit => ElectricCurrentDensityUnit.AmperePerSquareMeter; /// /// All units of measurement for the ElectricCurrentDensity quantity. /// public static ElectricCurrentDensityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().ToArray(); - /// /// Get ElectricCurrentDensity in AmperesPerSquareMeter. /// - public double AmperesPerSquareMeter - { - get { return _amperesPerSquareMeter; } - } + public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); #endregion #region Static - public static ElectricCurrentDensity Zero - { - get { return new ElectricCurrentDensity(); } - } + public static ElectricCurrentDensity Zero => new ElectricCurrentDensity(0, BaseUnit); /// /// Get ElectricCurrentDensity from AmperesPerSquareMeter. @@ -152,17 +179,13 @@ public static ElectricCurrentDensity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricCurrentDensity FromAmperesPerSquareMeter(double amperespersquaremeter) - { - double value = (double) amperespersquaremeter; - return new ElectricCurrentDensity(value); - } #else public static ElectricCurrentDensity FromAmperesPerSquareMeter(QuantityValue amperespersquaremeter) +#endif { double value = (double) amperespersquaremeter; - return new ElectricCurrentDensity((value)); + return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static ElectricCurrentDensity From(double value, ElectricCurrentDensityUn public static ElectricCurrentDensity From(QuantityValue value, ElectricCurrentDensityUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricCurrentDensityUnit.AmperePerSquareMeter: - return FromAmperesPerSquareMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricCurrentDensity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static ElectricCurrentDensity From(QuantityValue value, ElectricCurrentDe { return null; } - switch (fromUnit) - { - case ElectricCurrentDensityUnit.AmperePerSquareMeter: - return FromAmperesPerSquareMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricCurrentDensity((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(ElectricCurrentDensityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentDensityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricCurrentDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(ElectricCurrentDensityUnit unit, [CanBeNull #if !WINDOWS_UWP public static ElectricCurrentDensity operator -(ElectricCurrentDensity right) { - return new ElectricCurrentDensity(-right._amperesPerSquareMeter); + return new ElectricCurrentDensity(-right.Value, right.Unit); } public static ElectricCurrentDensity operator +(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return new ElectricCurrentDensity(left._amperesPerSquareMeter + right._amperesPerSquareMeter); + return new ElectricCurrentDensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricCurrentDensity operator -(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return new ElectricCurrentDensity(left._amperesPerSquareMeter - right._amperesPerSquareMeter); + return new ElectricCurrentDensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricCurrentDensity operator *(double left, ElectricCurrentDensity right) { - return new ElectricCurrentDensity(left*right._amperesPerSquareMeter); + return new ElectricCurrentDensity(left * right.Value, right.Unit); } public static ElectricCurrentDensity operator *(ElectricCurrentDensity left, double right) { - return new ElectricCurrentDensity(left._amperesPerSquareMeter*(double)right); + return new ElectricCurrentDensity(left.Value * right, left.Unit); } public static ElectricCurrentDensity operator /(ElectricCurrentDensity left, double right) { - return new ElectricCurrentDensity(left._amperesPerSquareMeter/(double)right); + return new ElectricCurrentDensity(left.Value / right, left.Unit); } public static double operator /(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return Convert.ToDouble(left._amperesPerSquareMeter/right._amperesPerSquareMeter); + return left.AmperesPerSquareMeter / right.AmperesPerSquareMeter; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricCurrentDensity other) { - return _amperesPerSquareMeter.CompareTo(other._amperesPerSquareMeter); + return AsBaseUnitAmperesPerSquareMeter().CompareTo(other.AsBaseUnitAmperesPerSquareMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return left._amperesPerSquareMeter <= right._amperesPerSquareMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return left._amperesPerSquareMeter >= right._amperesPerSquareMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return left._amperesPerSquareMeter < right._amperesPerSquareMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return left._amperesPerSquareMeter > right._amperesPerSquareMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricCurrentDensity left, ElectricCurrentDensity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._amperesPerSquareMeter == right._amperesPerSquareMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricCurrentDensity left, ElectricCurrentDensity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._amperesPerSquareMeter != right._amperesPerSquareMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _amperesPerSquareMeter.Equals(((ElectricCurrentDensity) obj)._amperesPerSquareMeter); + return AsBaseUnitAmperesPerSquareMeter().Equals(((ElectricCurrentDensity) obj).AsBaseUnitAmperesPerSquareMeter()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricCurrentDensity other, ElectricCurrentDensity maxError) { - return Math.Abs(_amperesPerSquareMeter - other._amperesPerSquareMeter) <= maxError._amperesPerSquareMeter; + return Math.Abs(AsBaseUnitAmperesPerSquareMeter() - other.AsBaseUnitAmperesPerSquareMeter()) <= maxError.AsBaseUnitAmperesPerSquareMeter(); } public override int GetHashCode() { - return _amperesPerSquareMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricCurrentDensityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitAmperesPerSquareMeter(); + switch (unit) { - case ElectricCurrentDensityUnit.AmperePerSquareMeter: - return AmperesPerSquareMeter; + case ElectricCurrentDensityUnit.AmperePerSquareMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static ElectricCurrentDensity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static ElectricCurrentDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricCurrentDensity Parse(string str, [CanBeNull] Culture culture) + public static ElectricCurrentDensity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricCurrentDensity r /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricCurrentDensity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricCurrentDensity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static ElectricCurrentDensityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricCurrentDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static ElectricCurrentDensityUnit ParseUnit(string str, [CanBeNull] strin /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static ElectricCurrentDensityUnit ParseUnit(string str, [CanBeNull] strin #else public #endif - static ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricCurrentDensityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentDensityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider formatPr #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is AmperePerSquareMeter /// @@ -587,7 +662,7 @@ static ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider formatPr /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(ElectricCurrentDensityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricCurrentDensityUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricCurrentDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricCurrentDensityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricCurrentDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricCurrentDensityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricCurrentDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricCurrentDensity /// - public static ElectricCurrentDensity MaxValue - { - get - { - return new ElectricCurrentDensity(double.MaxValue); - } - } + public static ElectricCurrentDensity MaxValue => new ElectricCurrentDensity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricCurrentDensity /// - public static ElectricCurrentDensity MinValue + public static ElectricCurrentDensity MinValue => new ElectricCurrentDensity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitAmperesPerSquareMeter() { - get + if (Unit == ElectricCurrentDensityUnit.AmperePerSquareMeter) { return _value; } + + switch (Unit) { - return new ElectricCurrentDensity(double.MinValue); - } - } - } + case ElectricCurrentDensityUnit.AmperePerSquareMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricCurrentDensityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs index 92a9034ee9..024cd4b077 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricCurrentGradient : IComparable, IComparable - /// Base unit of ElectricCurrentGradient. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricCurrentGradientUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _amperesPerSecond; + public ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricCurrentGradient() : this(0) + public ElectricCurrentGradient() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricCurrentGradient(double amperespersecond) { - _amperesPerSecond = Convert.ToDouble(amperespersecond); + _value = Convert.ToDouble(amperespersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricCurrentGradient(double numericValue, ElectricCurrentGradientUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit AmperePerSecond. + /// + /// Value assuming base unit AmperePerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricCurrentGradient(long amperespersecond) - { - _amperesPerSecond = Convert.ToDouble(amperespersecond); - } + ElectricCurrentGradient(long amperespersecond) : this(Convert.ToDouble(amperespersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit AmperePerSecond. + /// + /// Value assuming base unit AmperePerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricCurrentGradient(decimal amperespersecond) - { - _amperesPerSecond = Convert.ToDouble(amperespersecond); - } + ElectricCurrentGradient(decimal amperespersecond) : this(Convert.ToDouble(amperespersecond), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public ElectricCurrentGradient(double amperespersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricCurrentGradientUnit BaseUnit - { - get { return ElectricCurrentGradientUnit.AmperePerSecond; } - } + public static ElectricCurrentGradientUnit BaseUnit => ElectricCurrentGradientUnit.AmperePerSecond; /// /// All units of measurement for the ElectricCurrentGradient quantity. /// public static ElectricCurrentGradientUnit[] Units { get; } = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().ToArray(); - /// /// Get ElectricCurrentGradient in AmperesPerSecond. /// - public double AmperesPerSecond - { - get { return _amperesPerSecond; } - } + public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); #endregion #region Static - public static ElectricCurrentGradient Zero - { - get { return new ElectricCurrentGradient(); } - } + public static ElectricCurrentGradient Zero => new ElectricCurrentGradient(0, BaseUnit); /// /// Get ElectricCurrentGradient from AmperesPerSecond. @@ -152,17 +179,13 @@ public static ElectricCurrentGradient Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricCurrentGradient FromAmperesPerSecond(double amperespersecond) - { - double value = (double) amperespersecond; - return new ElectricCurrentGradient(value); - } #else public static ElectricCurrentGradient FromAmperesPerSecond(QuantityValue amperespersecond) +#endif { double value = (double) amperespersecond; - return new ElectricCurrentGradient((value)); + return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerSecond); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static ElectricCurrentGradient From(double value, ElectricCurrentGradient public static ElectricCurrentGradient From(QuantityValue value, ElectricCurrentGradientUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricCurrentGradientUnit.AmperePerSecond: - return FromAmperesPerSecond(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricCurrentGradient((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static ElectricCurrentGradient From(QuantityValue value, ElectricCurrentG { return null; } - switch (fromUnit) - { - case ElectricCurrentGradientUnit.AmperePerSecond: - return FromAmperesPerSecond(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricCurrentGradient((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(ElectricCurrentGradientUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricCurrentGradientUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricCurrentGradientUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(ElectricCurrentGradientUnit unit, [CanBeNul #if !WINDOWS_UWP public static ElectricCurrentGradient operator -(ElectricCurrentGradient right) { - return new ElectricCurrentGradient(-right._amperesPerSecond); + return new ElectricCurrentGradient(-right.Value, right.Unit); } public static ElectricCurrentGradient operator +(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return new ElectricCurrentGradient(left._amperesPerSecond + right._amperesPerSecond); + return new ElectricCurrentGradient(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricCurrentGradient operator -(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return new ElectricCurrentGradient(left._amperesPerSecond - right._amperesPerSecond); + return new ElectricCurrentGradient(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricCurrentGradient operator *(double left, ElectricCurrentGradient right) { - return new ElectricCurrentGradient(left*right._amperesPerSecond); + return new ElectricCurrentGradient(left * right.Value, right.Unit); } public static ElectricCurrentGradient operator *(ElectricCurrentGradient left, double right) { - return new ElectricCurrentGradient(left._amperesPerSecond*(double)right); + return new ElectricCurrentGradient(left.Value * right, left.Unit); } public static ElectricCurrentGradient operator /(ElectricCurrentGradient left, double right) { - return new ElectricCurrentGradient(left._amperesPerSecond/(double)right); + return new ElectricCurrentGradient(left.Value / right, left.Unit); } public static double operator /(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return Convert.ToDouble(left._amperesPerSecond/right._amperesPerSecond); + return left.AmperesPerSecond / right.AmperesPerSecond; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricCurrentGradient other) { - return _amperesPerSecond.CompareTo(other._amperesPerSecond); + return AsBaseUnitAmperesPerSecond().CompareTo(other.AsBaseUnitAmperesPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return left._amperesPerSecond <= right._amperesPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return left._amperesPerSecond >= right._amperesPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return left._amperesPerSecond < right._amperesPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return left._amperesPerSecond > right._amperesPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricCurrentGradient left, ElectricCurrentGradient right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._amperesPerSecond == right._amperesPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricCurrentGradient left, ElectricCurrentGradient right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._amperesPerSecond != right._amperesPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _amperesPerSecond.Equals(((ElectricCurrentGradient) obj)._amperesPerSecond); + return AsBaseUnitAmperesPerSecond().Equals(((ElectricCurrentGradient) obj).AsBaseUnitAmperesPerSecond()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricCurrentGradient other, ElectricCurrentGradient maxError) { - return Math.Abs(_amperesPerSecond - other._amperesPerSecond) <= maxError._amperesPerSecond; + return Math.Abs(AsBaseUnitAmperesPerSecond() - other.AsBaseUnitAmperesPerSecond()) <= maxError.AsBaseUnitAmperesPerSecond(); } public override int GetHashCode() { - return _amperesPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricCurrentGradientUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitAmperesPerSecond(); + switch (unit) { - case ElectricCurrentGradientUnit.AmperePerSecond: - return AmperesPerSecond; + case ElectricCurrentGradientUnit.AmperePerSecond: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static ElectricCurrentGradient Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static ElectricCurrentGradient Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricCurrentGradient Parse(string str, [CanBeNull] Culture culture) + public static ElectricCurrentGradient Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricCurrentGradient /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricCurrentGradient result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricCurrentGradient result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static ElectricCurrentGradientUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricCurrentGradientUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static ElectricCurrentGradientUnit ParseUnit(string str, [CanBeNull] stri /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static ElectricCurrentGradientUnit ParseUnit(string str, [CanBeNull] stri #else public #endif - static ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricCurrentGradientUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricCurrentGradientUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider formatP #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is AmperePerSecond /// @@ -587,7 +662,7 @@ static ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider formatP /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(ElectricCurrentGradientUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricCurrentGradientUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricCurrentGradientUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricCurrentGradientUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricCurrentGradientUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricCurrentGradientUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricCurrentGradientUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricCurrentGradient /// - public static ElectricCurrentGradient MaxValue - { - get - { - return new ElectricCurrentGradient(double.MaxValue); - } - } + public static ElectricCurrentGradient MaxValue => new ElectricCurrentGradient(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricCurrentGradient /// - public static ElectricCurrentGradient MinValue + public static ElectricCurrentGradient MinValue => new ElectricCurrentGradient(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitAmperesPerSecond() { - get + if (Unit == ElectricCurrentGradientUnit.AmperePerSecond) { return _value; } + + switch (Unit) { - return new ElectricCurrentGradient(double.MinValue); - } - } - } + case ElectricCurrentGradientUnit.AmperePerSecond: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricCurrentGradientUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs index 2b9bf4f159..3e8f743b3d 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricField : IComparable, IComparable #endif { /// - /// Base unit of ElectricField. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricFieldUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _voltsPerMeter; + public ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricField() : this(0) + public ElectricField() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricField(double voltspermeter) { - _voltsPerMeter = Convert.ToDouble(voltspermeter); + _value = Convert.ToDouble(voltspermeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricField(double numericValue, ElectricFieldUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit VoltPerMeter. + /// + /// Value assuming base unit VoltPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricField(long voltspermeter) - { - _voltsPerMeter = Convert.ToDouble(voltspermeter); - } + ElectricField(long voltspermeter) : this(Convert.ToDouble(voltspermeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit VoltPerMeter. + /// + /// Value assuming base unit VoltPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricField(decimal voltspermeter) - { - _voltsPerMeter = Convert.ToDouble(voltspermeter); - } + ElectricField(decimal voltspermeter) : this(Convert.ToDouble(voltspermeter), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public ElectricField(double voltspermeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricFieldUnit BaseUnit - { - get { return ElectricFieldUnit.VoltPerMeter; } - } + public static ElectricFieldUnit BaseUnit => ElectricFieldUnit.VoltPerMeter; /// /// All units of measurement for the ElectricField quantity. /// public static ElectricFieldUnit[] Units { get; } = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().ToArray(); - /// /// Get ElectricField in VoltsPerMeter. /// - public double VoltsPerMeter - { - get { return _voltsPerMeter; } - } + public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); #endregion #region Static - public static ElectricField Zero - { - get { return new ElectricField(); } - } + public static ElectricField Zero => new ElectricField(0, BaseUnit); /// /// Get ElectricField from VoltsPerMeter. @@ -152,17 +179,13 @@ public static ElectricField Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricField FromVoltsPerMeter(double voltspermeter) - { - double value = (double) voltspermeter; - return new ElectricField(value); - } #else public static ElectricField FromVoltsPerMeter(QuantityValue voltspermeter) +#endif { double value = (double) voltspermeter; - return new ElectricField((value)); + return new ElectricField(value, ElectricFieldUnit.VoltPerMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static ElectricField From(double value, ElectricFieldUnit fromUnit) public static ElectricField From(QuantityValue value, ElectricFieldUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricFieldUnit.VoltPerMeter: - return FromVoltsPerMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricField((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static ElectricField From(QuantityValue value, ElectricFieldUnit fromUnit { return null; } - switch (fromUnit) - { - case ElectricFieldUnit.VoltPerMeter: - return FromVoltsPerMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricField((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(ElectricFieldUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricFieldUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricFieldUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(ElectricFieldUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static ElectricField operator -(ElectricField right) { - return new ElectricField(-right._voltsPerMeter); + return new ElectricField(-right.Value, right.Unit); } public static ElectricField operator +(ElectricField left, ElectricField right) { - return new ElectricField(left._voltsPerMeter + right._voltsPerMeter); + return new ElectricField(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricField operator -(ElectricField left, ElectricField right) { - return new ElectricField(left._voltsPerMeter - right._voltsPerMeter); + return new ElectricField(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricField operator *(double left, ElectricField right) { - return new ElectricField(left*right._voltsPerMeter); + return new ElectricField(left * right.Value, right.Unit); } public static ElectricField operator *(ElectricField left, double right) { - return new ElectricField(left._voltsPerMeter*(double)right); + return new ElectricField(left.Value * right, left.Unit); } public static ElectricField operator /(ElectricField left, double right) { - return new ElectricField(left._voltsPerMeter/(double)right); + return new ElectricField(left.Value / right, left.Unit); } public static double operator /(ElectricField left, ElectricField right) { - return Convert.ToDouble(left._voltsPerMeter/right._voltsPerMeter); + return left.VoltsPerMeter / right.VoltsPerMeter; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricField other) { - return _voltsPerMeter.CompareTo(other._voltsPerMeter); + return AsBaseUnitVoltsPerMeter().CompareTo(other.AsBaseUnitVoltsPerMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricField left, ElectricField right) { - return left._voltsPerMeter <= right._voltsPerMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricField left, ElectricField right) { - return left._voltsPerMeter >= right._voltsPerMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricField left, ElectricField right) { - return left._voltsPerMeter < right._voltsPerMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricField left, ElectricField right) { - return left._voltsPerMeter > right._voltsPerMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricField left, ElectricField right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltsPerMeter == right._voltsPerMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricField left, ElectricField right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltsPerMeter != right._voltsPerMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _voltsPerMeter.Equals(((ElectricField) obj)._voltsPerMeter); + return AsBaseUnitVoltsPerMeter().Equals(((ElectricField) obj).AsBaseUnitVoltsPerMeter()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricField other, ElectricField maxError) { - return Math.Abs(_voltsPerMeter - other._voltsPerMeter) <= maxError._voltsPerMeter; + return Math.Abs(AsBaseUnitVoltsPerMeter() - other.AsBaseUnitVoltsPerMeter()) <= maxError.AsBaseUnitVoltsPerMeter(); } public override int GetHashCode() { - return _voltsPerMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricFieldUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitVoltsPerMeter(); + switch (unit) { - case ElectricFieldUnit.VoltPerMeter: - return VoltsPerMeter; + case ElectricFieldUnit.VoltPerMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static ElectricField Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static ElectricField Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricField Parse(string str, [CanBeNull] Culture culture) + public static ElectricField Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricField result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricField result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricField result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static ElectricFieldUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricFieldUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static ElectricFieldUnit ParseUnit(string str, [CanBeNull] string culture /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static ElectricFieldUnit ParseUnit(string str, [CanBeNull] string culture #else public #endif - static ElectricFieldUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricFieldUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricFieldUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricFieldUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static ElectricFieldUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is VoltPerMeter /// @@ -587,7 +662,7 @@ static ElectricFieldUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(ElectricFieldUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricFieldUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricFieldUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricFieldUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricFieldUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricFieldUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricFieldUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricField /// - public static ElectricField MaxValue - { - get - { - return new ElectricField(double.MaxValue); - } - } + public static ElectricField MaxValue => new ElectricField(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricField /// - public static ElectricField MinValue + public static ElectricField MinValue => new ElectricField(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitVoltsPerMeter() { - get + if (Unit == ElectricFieldUnit.VoltPerMeter) { return _value; } + + switch (Unit) { - return new ElectricField(double.MinValue); - } - } - } + case ElectricFieldUnit.VoltPerMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricFieldUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs index 589889c70e..0e1b05f712 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricInductance : IComparable, IComparable - /// Base unit of ElectricInductance. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricInductanceUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _henries; + public ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricInductance() : this(0) + public ElectricInductance() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricInductance(double henries) { - _henries = Convert.ToDouble(henries); + _value = Convert.ToDouble(henries); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricInductance(double numericValue, ElectricInductanceUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Henry. + /// + /// Value assuming base unit Henry. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricInductance(long henries) - { - _henries = Convert.ToDouble(henries); - } + ElectricInductance(long henries) : this(Convert.ToDouble(henries), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Henry. + /// + /// Value assuming base unit Henry. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricInductance(decimal henries) - { - _henries = Convert.ToDouble(henries); - } + ElectricInductance(decimal henries) : this(Convert.ToDouble(henries), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public ElectricInductance(double henries) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricInductanceUnit BaseUnit - { - get { return ElectricInductanceUnit.Henry; } - } + public static ElectricInductanceUnit BaseUnit => ElectricInductanceUnit.Henry; /// /// All units of measurement for the ElectricInductance quantity. /// public static ElectricInductanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().ToArray(); - /// /// Get ElectricInductance in Henries. /// - public double Henries - { - get { return _henries; } - } + public double Henries => As(ElectricInductanceUnit.Henry); #endregion #region Static - public static ElectricInductance Zero - { - get { return new ElectricInductance(); } - } + public static ElectricInductance Zero => new ElectricInductance(0, BaseUnit); /// /// Get ElectricInductance from Henries. @@ -152,17 +179,13 @@ public static ElectricInductance Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricInductance FromHenries(double henries) - { - double value = (double) henries; - return new ElectricInductance(value); - } #else public static ElectricInductance FromHenries(QuantityValue henries) +#endif { double value = (double) henries; - return new ElectricInductance((value)); + return new ElectricInductance(value, ElectricInductanceUnit.Henry); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static ElectricInductance From(double value, ElectricInductanceUnit fromU public static ElectricInductance From(QuantityValue value, ElectricInductanceUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricInductanceUnit.Henry: - return FromHenries(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricInductance((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static ElectricInductance From(QuantityValue value, ElectricInductanceUni { return null; } - switch (fromUnit) - { - case ElectricInductanceUnit.Henry: - return FromHenries(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricInductance((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(ElectricInductanceUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricInductanceUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricInductanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(ElectricInductanceUnit unit, [CanBeNull] Cu #if !WINDOWS_UWP public static ElectricInductance operator -(ElectricInductance right) { - return new ElectricInductance(-right._henries); + return new ElectricInductance(-right.Value, right.Unit); } public static ElectricInductance operator +(ElectricInductance left, ElectricInductance right) { - return new ElectricInductance(left._henries + right._henries); + return new ElectricInductance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricInductance operator -(ElectricInductance left, ElectricInductance right) { - return new ElectricInductance(left._henries - right._henries); + return new ElectricInductance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricInductance operator *(double left, ElectricInductance right) { - return new ElectricInductance(left*right._henries); + return new ElectricInductance(left * right.Value, right.Unit); } public static ElectricInductance operator *(ElectricInductance left, double right) { - return new ElectricInductance(left._henries*(double)right); + return new ElectricInductance(left.Value * right, left.Unit); } public static ElectricInductance operator /(ElectricInductance left, double right) { - return new ElectricInductance(left._henries/(double)right); + return new ElectricInductance(left.Value / right, left.Unit); } public static double operator /(ElectricInductance left, ElectricInductance right) { - return Convert.ToDouble(left._henries/right._henries); + return left.Henries / right.Henries; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricInductance other) { - return _henries.CompareTo(other._henries); + return AsBaseUnitHenries().CompareTo(other.AsBaseUnitHenries()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricInductance left, ElectricInductance right) { - return left._henries <= right._henries; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricInductance left, ElectricInductance right) { - return left._henries >= right._henries; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricInductance left, ElectricInductance right) { - return left._henries < right._henries; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricInductance left, ElectricInductance right) { - return left._henries > right._henries; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricInductance left, ElectricInductance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._henries == right._henries; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricInductance left, ElectricInductance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._henries != right._henries; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _henries.Equals(((ElectricInductance) obj)._henries); + return AsBaseUnitHenries().Equals(((ElectricInductance) obj).AsBaseUnitHenries()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricInductance other, ElectricInductance maxError) { - return Math.Abs(_henries - other._henries) <= maxError._henries; + return Math.Abs(AsBaseUnitHenries() - other.AsBaseUnitHenries()) <= maxError.AsBaseUnitHenries(); } public override int GetHashCode() { - return _henries.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricInductanceUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitHenries(); + switch (unit) { - case ElectricInductanceUnit.Henry: - return Henries; + case ElectricInductanceUnit.Henry: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static ElectricInductance Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static ElectricInductance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricInductance Parse(string str, [CanBeNull] Culture culture) + public static ElectricInductance Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricInductance resul /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricInductance result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricInductance result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static ElectricInductanceUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricInductanceUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static ElectricInductanceUnit ParseUnit(string str, [CanBeNull] string cu /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static ElectricInductanceUnit ParseUnit(string str, [CanBeNull] string cu #else public #endif - static ElectricInductanceUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricInductanceUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricInductanceUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricInductanceUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static ElectricInductanceUnit ParseUnit(string str, IFormatProvider formatProvid #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Henry /// @@ -587,7 +662,7 @@ static ElectricInductanceUnit ParseUnit(string str, IFormatProvider formatProvid /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(ElectricInductanceUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricInductanceUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricInductanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricInductanceUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricInductanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricInductanceUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricInductanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricInductance /// - public static ElectricInductance MaxValue - { - get - { - return new ElectricInductance(double.MaxValue); - } - } + public static ElectricInductance MaxValue => new ElectricInductance(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricInductance /// - public static ElectricInductance MinValue + public static ElectricInductance MinValue => new ElectricInductance(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitHenries() { - get + if (Unit == ElectricInductanceUnit.Henry) { return _value; } + + switch (Unit) { - return new ElectricInductance(double.MinValue); - } - } - } + case ElectricInductanceUnit.Henry: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricInductanceUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs index 936e6f76dd..ba778b5274 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricPotential : IComparable, IComparable - /// Base unit of ElectricPotential. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _volts; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricPotential() : this(0) + public ElectricPotential() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricPotential(double volts) { - _volts = Convert.ToDouble(volts); + _value = Convert.ToDouble(volts); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricPotential(double numericValue, ElectricPotentialUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Volt. + /// + /// Value assuming base unit Volt. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricPotential(long volts) - { - _volts = Convert.ToDouble(volts); - } + ElectricPotential(long volts) : this(Convert.ToDouble(volts), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Volt. + /// + /// Value assuming base unit Volt. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricPotential(decimal volts) - { - _volts = Convert.ToDouble(volts); - } + ElectricPotential(decimal volts) : this(Convert.ToDouble(volts), BaseUnit) { } #region Properties @@ -119,64 +156,38 @@ public ElectricPotential(double volts) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricPotentialUnit BaseUnit - { - get { return ElectricPotentialUnit.Volt; } - } + public static ElectricPotentialUnit BaseUnit => ElectricPotentialUnit.Volt; /// /// All units of measurement for the ElectricPotential quantity. /// public static ElectricPotentialUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().ToArray(); - /// /// Get ElectricPotential in Kilovolts. /// - public double Kilovolts - { - get { return (_volts) / 1e3d; } - } - + public double Kilovolts => As(ElectricPotentialUnit.Kilovolt); /// /// Get ElectricPotential in Megavolts. /// - public double Megavolts - { - get { return (_volts) / 1e6d; } - } - + public double Megavolts => As(ElectricPotentialUnit.Megavolt); /// /// Get ElectricPotential in Microvolts. /// - public double Microvolts - { - get { return (_volts) / 1e-6d; } - } - + public double Microvolts => As(ElectricPotentialUnit.Microvolt); /// /// Get ElectricPotential in Millivolts. /// - public double Millivolts - { - get { return (_volts) / 1e-3d; } - } - + public double Millivolts => As(ElectricPotentialUnit.Millivolt); /// /// Get ElectricPotential in Volts. /// - public double Volts - { - get { return _volts; } - } + public double Volts => As(ElectricPotentialUnit.Volt); #endregion #region Static - public static ElectricPotential Zero - { - get { return new ElectricPotential(); } - } + public static ElectricPotential Zero => new ElectricPotential(0, BaseUnit); /// /// Get ElectricPotential from Kilovolts. @@ -184,17 +195,13 @@ public static ElectricPotential Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotential FromKilovolts(double kilovolts) - { - double value = (double) kilovolts; - return new ElectricPotential((value) * 1e3d); - } #else public static ElectricPotential FromKilovolts(QuantityValue kilovolts) +#endif { double value = (double) kilovolts; - return new ElectricPotential(((value) * 1e3d)); + return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); } -#endif /// /// Get ElectricPotential from Megavolts. @@ -202,17 +209,13 @@ public static ElectricPotential FromKilovolts(QuantityValue kilovolts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotential FromMegavolts(double megavolts) - { - double value = (double) megavolts; - return new ElectricPotential((value) * 1e6d); - } #else public static ElectricPotential FromMegavolts(QuantityValue megavolts) +#endif { double value = (double) megavolts; - return new ElectricPotential(((value) * 1e6d)); + return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); } -#endif /// /// Get ElectricPotential from Microvolts. @@ -220,17 +223,13 @@ public static ElectricPotential FromMegavolts(QuantityValue megavolts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotential FromMicrovolts(double microvolts) - { - double value = (double) microvolts; - return new ElectricPotential((value) * 1e-6d); - } #else public static ElectricPotential FromMicrovolts(QuantityValue microvolts) +#endif { double value = (double) microvolts; - return new ElectricPotential(((value) * 1e-6d)); + return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); } -#endif /// /// Get ElectricPotential from Millivolts. @@ -238,17 +237,13 @@ public static ElectricPotential FromMicrovolts(QuantityValue microvolts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotential FromMillivolts(double millivolts) - { - double value = (double) millivolts; - return new ElectricPotential((value) * 1e-3d); - } #else public static ElectricPotential FromMillivolts(QuantityValue millivolts) +#endif { double value = (double) millivolts; - return new ElectricPotential(((value) * 1e-3d)); + return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); } -#endif /// /// Get ElectricPotential from Volts. @@ -256,17 +251,13 @@ public static ElectricPotential FromMillivolts(QuantityValue millivolts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotential FromVolts(double volts) - { - double value = (double) volts; - return new ElectricPotential(value); - } #else public static ElectricPotential FromVolts(QuantityValue volts) +#endif { double value = (double) volts; - return new ElectricPotential((value)); + return new ElectricPotential(value, ElectricPotentialUnit.Volt); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -361,22 +352,7 @@ public static ElectricPotential From(double value, ElectricPotentialUnit fromUni public static ElectricPotential From(QuantityValue value, ElectricPotentialUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricPotentialUnit.Kilovolt: - return FromKilovolts(value); - case ElectricPotentialUnit.Megavolt: - return FromMegavolts(value); - case ElectricPotentialUnit.Microvolt: - return FromMicrovolts(value); - case ElectricPotentialUnit.Millivolt: - return FromMillivolts(value); - case ElectricPotentialUnit.Volt: - return FromVolts(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricPotential((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -393,22 +369,8 @@ public static ElectricPotential From(QuantityValue value, ElectricPotentialUnit { return null; } - switch (fromUnit) - { - case ElectricPotentialUnit.Kilovolt: - return FromKilovolts(value.Value); - case ElectricPotentialUnit.Megavolt: - return FromMegavolts(value.Value); - case ElectricPotentialUnit.Microvolt: - return FromMicrovolts(value.Value); - case ElectricPotentialUnit.Millivolt: - return FromMillivolts(value.Value); - case ElectricPotentialUnit.Volt: - return FromVolts(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricPotential((double)value.Value, fromUnit); } #endif @@ -427,12 +389,29 @@ public static string GetAbbreviation(ElectricPotentialUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricPotentialUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -443,37 +422,37 @@ public static string GetAbbreviation(ElectricPotentialUnit unit, [CanBeNull] Cul #if !WINDOWS_UWP public static ElectricPotential operator -(ElectricPotential right) { - return new ElectricPotential(-right._volts); + return new ElectricPotential(-right.Value, right.Unit); } public static ElectricPotential operator +(ElectricPotential left, ElectricPotential right) { - return new ElectricPotential(left._volts + right._volts); + return new ElectricPotential(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricPotential operator -(ElectricPotential left, ElectricPotential right) { - return new ElectricPotential(left._volts - right._volts); + return new ElectricPotential(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricPotential operator *(double left, ElectricPotential right) { - return new ElectricPotential(left*right._volts); + return new ElectricPotential(left * right.Value, right.Unit); } public static ElectricPotential operator *(ElectricPotential left, double right) { - return new ElectricPotential(left._volts*(double)right); + return new ElectricPotential(left.Value * right, left.Unit); } public static ElectricPotential operator /(ElectricPotential left, double right) { - return new ElectricPotential(left._volts/(double)right); + return new ElectricPotential(left.Value / right, left.Unit); } public static double operator /(ElectricPotential left, ElectricPotential right) { - return Convert.ToDouble(left._volts/right._volts); + return left.Volts / right.Volts; } #endif @@ -496,43 +475,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricPotential other) { - return _volts.CompareTo(other._volts); + return AsBaseUnitVolts().CompareTo(other.AsBaseUnitVolts()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricPotential left, ElectricPotential right) { - return left._volts <= right._volts; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricPotential left, ElectricPotential right) { - return left._volts >= right._volts; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricPotential left, ElectricPotential right) { - return left._volts < right._volts; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricPotential left, ElectricPotential right) { - return left._volts > right._volts; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricPotential left, ElectricPotential right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._volts == right._volts; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricPotential left, ElectricPotential right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._volts != right._volts; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -544,7 +523,7 @@ public override bool Equals(object obj) return false; } - return _volts.Equals(((ElectricPotential) obj)._volts); + return AsBaseUnitVolts().Equals(((ElectricPotential) obj).AsBaseUnitVolts()); } /// @@ -557,12 +536,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricPotential other, ElectricPotential maxError) { - return Math.Abs(_volts - other._volts) <= maxError._volts; + return Math.Abs(AsBaseUnitVolts() - other.AsBaseUnitVolts()) <= maxError.AsBaseUnitVolts(); } public override int GetHashCode() { - return _volts.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -572,22 +551,23 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricPotentialUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitVolts(); + switch (unit) { - case ElectricPotentialUnit.Kilovolt: - return Kilovolts; - case ElectricPotentialUnit.Megavolt: - return Megavolts; - case ElectricPotentialUnit.Microvolt: - return Microvolts; - case ElectricPotentialUnit.Millivolt: - return Millivolts; - case ElectricPotentialUnit.Volt: - return Volts; + case ElectricPotentialUnit.Kilovolt: return (baseUnitValue) / 1e3d; + case ElectricPotentialUnit.Megavolt: return (baseUnitValue) / 1e6d; + case ElectricPotentialUnit.Microvolt: return (baseUnitValue) / 1e-6d; + case ElectricPotentialUnit.Millivolt: return (baseUnitValue) / 1e-3d; + case ElectricPotentialUnit.Volt: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -629,7 +609,11 @@ public static ElectricPotential Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -648,17 +632,24 @@ public static ElectricPotential Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricPotential Parse(string str, [CanBeNull] Culture culture) + public static ElectricPotential Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -684,16 +675,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricPotential result /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricPotential result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricPotential result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -706,6 +722,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -719,11 +736,14 @@ public static ElectricPotentialUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricPotentialUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -732,6 +752,8 @@ public static ElectricPotentialUnit ParseUnit(string str, [CanBeNull] string cul /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -744,18 +766,18 @@ public static ElectricPotentialUnit ParseUnit(string str, [CanBeNull] string cul #else public #endif - static ElectricPotentialUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricPotentialUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricPotentialUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -764,6 +786,7 @@ static ElectricPotentialUnit ParseUnit(string str, IFormatProvider formatProvide #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Volt /// @@ -775,7 +798,7 @@ static ElectricPotentialUnit ParseUnit(string str, IFormatProvider formatProvide /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -792,74 +815,133 @@ public string ToString(ElectricPotentialUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricPotentialUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricPotentialUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricPotentialUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricPotentialUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricPotentialUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricPotentialUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricPotential /// - public static ElectricPotential MaxValue - { - get - { - return new ElectricPotential(double.MaxValue); - } - } + public static ElectricPotential MaxValue => new ElectricPotential(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricPotential /// - public static ElectricPotential MinValue + public static ElectricPotential MinValue => new ElectricPotential(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitVolts() { - get + if (Unit == ElectricPotentialUnit.Volt) { return _value; } + + switch (Unit) { - return new ElectricPotential(double.MinValue); - } - } - } + case ElectricPotentialUnit.Kilovolt: return (_value) * 1e3d; + case ElectricPotentialUnit.Megavolt: return (_value) * 1e6d; + case ElectricPotentialUnit.Microvolt: return (_value) * 1e-6d; + case ElectricPotentialUnit.Millivolt: return (_value) * 1e-3d; + case ElectricPotentialUnit.Volt: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricPotentialUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs index a8f2406900..3e58f534c8 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricPotentialAc : IComparable, IComparable - /// Base unit of ElectricPotentialAc. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialAcUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _voltsAc; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricPotentialAcUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricPotentialAc() : this(0) + public ElectricPotentialAc() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricPotentialAc(double voltsac) { - _voltsAc = Convert.ToDouble(voltsac); + _value = Convert.ToDouble(voltsac); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricPotentialAc(double numericValue, ElectricPotentialAcUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit VoltAc. + /// + /// Value assuming base unit VoltAc. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricPotentialAc(long voltsac) - { - _voltsAc = Convert.ToDouble(voltsac); - } + ElectricPotentialAc(long voltsac) : this(Convert.ToDouble(voltsac), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit VoltAc. + /// + /// Value assuming base unit VoltAc. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricPotentialAc(decimal voltsac) - { - _voltsAc = Convert.ToDouble(voltsac); - } + ElectricPotentialAc(decimal voltsac) : this(Convert.ToDouble(voltsac), BaseUnit) { } #region Properties @@ -119,64 +156,38 @@ public ElectricPotentialAc(double voltsac) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricPotentialAcUnit BaseUnit - { - get { return ElectricPotentialAcUnit.VoltAc; } - } + public static ElectricPotentialAcUnit BaseUnit => ElectricPotentialAcUnit.VoltAc; /// /// All units of measurement for the ElectricPotentialAc quantity. /// public static ElectricPotentialAcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast().ToArray(); - /// /// Get ElectricPotentialAc in KilovoltsAc. /// - public double KilovoltsAc - { - get { return (_voltsAc) / 1e3d; } - } - + public double KilovoltsAc => As(ElectricPotentialAcUnit.KilovoltAc); /// /// Get ElectricPotentialAc in MegavoltsAc. /// - public double MegavoltsAc - { - get { return (_voltsAc) / 1e6d; } - } - + public double MegavoltsAc => As(ElectricPotentialAcUnit.MegavoltAc); /// /// Get ElectricPotentialAc in MicrovoltsAc. /// - public double MicrovoltsAc - { - get { return (_voltsAc) / 1e-6d; } - } - + public double MicrovoltsAc => As(ElectricPotentialAcUnit.MicrovoltAc); /// /// Get ElectricPotentialAc in MillivoltsAc. /// - public double MillivoltsAc - { - get { return (_voltsAc) / 1e-3d; } - } - + public double MillivoltsAc => As(ElectricPotentialAcUnit.MillivoltAc); /// /// Get ElectricPotentialAc in VoltsAc. /// - public double VoltsAc - { - get { return _voltsAc; } - } + public double VoltsAc => As(ElectricPotentialAcUnit.VoltAc); #endregion #region Static - public static ElectricPotentialAc Zero - { - get { return new ElectricPotentialAc(); } - } + public static ElectricPotentialAc Zero => new ElectricPotentialAc(0, BaseUnit); /// /// Get ElectricPotentialAc from KilovoltsAc. @@ -184,17 +195,13 @@ public static ElectricPotentialAc Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotentialAc FromKilovoltsAc(double kilovoltsac) - { - double value = (double) kilovoltsac; - return new ElectricPotentialAc((value) * 1e3d); - } #else public static ElectricPotentialAc FromKilovoltsAc(QuantityValue kilovoltsac) +#endif { double value = (double) kilovoltsac; - return new ElectricPotentialAc(((value) * 1e3d)); + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc); } -#endif /// /// Get ElectricPotentialAc from MegavoltsAc. @@ -202,17 +209,13 @@ public static ElectricPotentialAc FromKilovoltsAc(QuantityValue kilovoltsac) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotentialAc FromMegavoltsAc(double megavoltsac) - { - double value = (double) megavoltsac; - return new ElectricPotentialAc((value) * 1e6d); - } #else public static ElectricPotentialAc FromMegavoltsAc(QuantityValue megavoltsac) +#endif { double value = (double) megavoltsac; - return new ElectricPotentialAc(((value) * 1e6d)); + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc); } -#endif /// /// Get ElectricPotentialAc from MicrovoltsAc. @@ -220,17 +223,13 @@ public static ElectricPotentialAc FromMegavoltsAc(QuantityValue megavoltsac) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotentialAc FromMicrovoltsAc(double microvoltsac) - { - double value = (double) microvoltsac; - return new ElectricPotentialAc((value) * 1e-6d); - } #else public static ElectricPotentialAc FromMicrovoltsAc(QuantityValue microvoltsac) +#endif { double value = (double) microvoltsac; - return new ElectricPotentialAc(((value) * 1e-6d)); + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc); } -#endif /// /// Get ElectricPotentialAc from MillivoltsAc. @@ -238,17 +237,13 @@ public static ElectricPotentialAc FromMicrovoltsAc(QuantityValue microvoltsac) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotentialAc FromMillivoltsAc(double millivoltsac) - { - double value = (double) millivoltsac; - return new ElectricPotentialAc((value) * 1e-3d); - } #else public static ElectricPotentialAc FromMillivoltsAc(QuantityValue millivoltsac) +#endif { double value = (double) millivoltsac; - return new ElectricPotentialAc(((value) * 1e-3d)); + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc); } -#endif /// /// Get ElectricPotentialAc from VoltsAc. @@ -256,17 +251,13 @@ public static ElectricPotentialAc FromMillivoltsAc(QuantityValue millivoltsac) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotentialAc FromVoltsAc(double voltsac) - { - double value = (double) voltsac; - return new ElectricPotentialAc(value); - } #else public static ElectricPotentialAc FromVoltsAc(QuantityValue voltsac) +#endif { double value = (double) voltsac; - return new ElectricPotentialAc((value)); + return new ElectricPotentialAc(value, ElectricPotentialAcUnit.VoltAc); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -361,22 +352,7 @@ public static ElectricPotentialAc From(double value, ElectricPotentialAcUnit fro public static ElectricPotentialAc From(QuantityValue value, ElectricPotentialAcUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricPotentialAcUnit.KilovoltAc: - return FromKilovoltsAc(value); - case ElectricPotentialAcUnit.MegavoltAc: - return FromMegavoltsAc(value); - case ElectricPotentialAcUnit.MicrovoltAc: - return FromMicrovoltsAc(value); - case ElectricPotentialAcUnit.MillivoltAc: - return FromMillivoltsAc(value); - case ElectricPotentialAcUnit.VoltAc: - return FromVoltsAc(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricPotentialAc((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -393,22 +369,8 @@ public static ElectricPotentialAc From(QuantityValue value, ElectricPotentialAcU { return null; } - switch (fromUnit) - { - case ElectricPotentialAcUnit.KilovoltAc: - return FromKilovoltsAc(value.Value); - case ElectricPotentialAcUnit.MegavoltAc: - return FromMegavoltsAc(value.Value); - case ElectricPotentialAcUnit.MicrovoltAc: - return FromMicrovoltsAc(value.Value); - case ElectricPotentialAcUnit.MillivoltAc: - return FromMillivoltsAc(value.Value); - case ElectricPotentialAcUnit.VoltAc: - return FromVoltsAc(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricPotentialAc((double)value.Value, fromUnit); } #endif @@ -427,12 +389,29 @@ public static string GetAbbreviation(ElectricPotentialAcUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricPotentialAcUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -443,37 +422,37 @@ public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] C #if !WINDOWS_UWP public static ElectricPotentialAc operator -(ElectricPotentialAc right) { - return new ElectricPotentialAc(-right._voltsAc); + return new ElectricPotentialAc(-right.Value, right.Unit); } public static ElectricPotentialAc operator +(ElectricPotentialAc left, ElectricPotentialAc right) { - return new ElectricPotentialAc(left._voltsAc + right._voltsAc); + return new ElectricPotentialAc(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricPotentialAc operator -(ElectricPotentialAc left, ElectricPotentialAc right) { - return new ElectricPotentialAc(left._voltsAc - right._voltsAc); + return new ElectricPotentialAc(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricPotentialAc operator *(double left, ElectricPotentialAc right) { - return new ElectricPotentialAc(left*right._voltsAc); + return new ElectricPotentialAc(left * right.Value, right.Unit); } public static ElectricPotentialAc operator *(ElectricPotentialAc left, double right) { - return new ElectricPotentialAc(left._voltsAc*(double)right); + return new ElectricPotentialAc(left.Value * right, left.Unit); } public static ElectricPotentialAc operator /(ElectricPotentialAc left, double right) { - return new ElectricPotentialAc(left._voltsAc/(double)right); + return new ElectricPotentialAc(left.Value / right, left.Unit); } public static double operator /(ElectricPotentialAc left, ElectricPotentialAc right) { - return Convert.ToDouble(left._voltsAc/right._voltsAc); + return left.VoltsAc / right.VoltsAc; } #endif @@ -496,43 +475,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricPotentialAc other) { - return _voltsAc.CompareTo(other._voltsAc); + return AsBaseUnitVoltsAc().CompareTo(other.AsBaseUnitVoltsAc()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricPotentialAc left, ElectricPotentialAc right) { - return left._voltsAc <= right._voltsAc; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricPotentialAc left, ElectricPotentialAc right) { - return left._voltsAc >= right._voltsAc; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricPotentialAc left, ElectricPotentialAc right) { - return left._voltsAc < right._voltsAc; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricPotentialAc left, ElectricPotentialAc right) { - return left._voltsAc > right._voltsAc; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricPotentialAc left, ElectricPotentialAc right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltsAc == right._voltsAc; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricPotentialAc left, ElectricPotentialAc right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltsAc != right._voltsAc; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -544,7 +523,7 @@ public override bool Equals(object obj) return false; } - return _voltsAc.Equals(((ElectricPotentialAc) obj)._voltsAc); + return AsBaseUnitVoltsAc().Equals(((ElectricPotentialAc) obj).AsBaseUnitVoltsAc()); } /// @@ -557,12 +536,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricPotentialAc other, ElectricPotentialAc maxError) { - return Math.Abs(_voltsAc - other._voltsAc) <= maxError._voltsAc; + return Math.Abs(AsBaseUnitVoltsAc() - other.AsBaseUnitVoltsAc()) <= maxError.AsBaseUnitVoltsAc(); } public override int GetHashCode() { - return _voltsAc.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -572,22 +551,23 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricPotentialAcUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitVoltsAc(); + switch (unit) { - case ElectricPotentialAcUnit.KilovoltAc: - return KilovoltsAc; - case ElectricPotentialAcUnit.MegavoltAc: - return MegavoltsAc; - case ElectricPotentialAcUnit.MicrovoltAc: - return MicrovoltsAc; - case ElectricPotentialAcUnit.MillivoltAc: - return MillivoltsAc; - case ElectricPotentialAcUnit.VoltAc: - return VoltsAc; + case ElectricPotentialAcUnit.KilovoltAc: return (baseUnitValue) / 1e3d; + case ElectricPotentialAcUnit.MegavoltAc: return (baseUnitValue) / 1e6d; + case ElectricPotentialAcUnit.MicrovoltAc: return (baseUnitValue) / 1e-6d; + case ElectricPotentialAcUnit.MillivoltAc: return (baseUnitValue) / 1e-3d; + case ElectricPotentialAcUnit.VoltAc: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -629,7 +609,11 @@ public static ElectricPotentialAc Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -648,17 +632,24 @@ public static ElectricPotentialAc Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricPotentialAc Parse(string str, [CanBeNull] Culture culture) + public static ElectricPotentialAc Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -684,16 +675,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricPotentialAc resu /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricPotentialAc result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricPotentialAc result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -706,6 +722,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -719,11 +736,14 @@ public static ElectricPotentialAcUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricPotentialAcUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -732,6 +752,8 @@ public static ElectricPotentialAcUnit ParseUnit(string str, [CanBeNull] string c /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -744,18 +766,18 @@ public static ElectricPotentialAcUnit ParseUnit(string str, [CanBeNull] string c #else public #endif - static ElectricPotentialAcUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricPotentialAcUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricPotentialAcUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialAcUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -764,6 +786,7 @@ static ElectricPotentialAcUnit ParseUnit(string str, IFormatProvider formatProvi #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is VoltAc /// @@ -775,7 +798,7 @@ static ElectricPotentialAcUnit ParseUnit(string str, IFormatProvider formatProvi /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -792,74 +815,133 @@ public string ToString(ElectricPotentialAcUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricPotentialAcUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricPotentialAcUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricPotentialAcUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricPotentialAcUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricPotentialAcUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricPotentialAcUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricPotentialAc /// - public static ElectricPotentialAc MaxValue - { - get - { - return new ElectricPotentialAc(double.MaxValue); - } - } + public static ElectricPotentialAc MaxValue => new ElectricPotentialAc(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricPotentialAc /// - public static ElectricPotentialAc MinValue + public static ElectricPotentialAc MinValue => new ElectricPotentialAc(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitVoltsAc() { - get + if (Unit == ElectricPotentialAcUnit.VoltAc) { return _value; } + + switch (Unit) { - return new ElectricPotentialAc(double.MinValue); - } - } - } + case ElectricPotentialAcUnit.KilovoltAc: return (_value) * 1e3d; + case ElectricPotentialAcUnit.MegavoltAc: return (_value) * 1e6d; + case ElectricPotentialAcUnit.MicrovoltAc: return (_value) * 1e-6d; + case ElectricPotentialAcUnit.MillivoltAc: return (_value) * 1e-3d; + case ElectricPotentialAcUnit.VoltAc: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricPotentialAcUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs index 53b10d5ca2..599f416d52 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialDc.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricPotentialDc : IComparable, IComparable - /// Base unit of ElectricPotentialDc. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ElectricPotentialDcUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _voltsDc; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricPotentialDcUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricPotentialDc() : this(0) + public ElectricPotentialDc() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricPotentialDc(double voltsdc) { - _voltsDc = Convert.ToDouble(voltsdc); + _value = Convert.ToDouble(voltsdc); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricPotentialDc(double numericValue, ElectricPotentialDcUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit VoltDc. + /// + /// Value assuming base unit VoltDc. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricPotentialDc(long voltsdc) - { - _voltsDc = Convert.ToDouble(voltsdc); - } + ElectricPotentialDc(long voltsdc) : this(Convert.ToDouble(voltsdc), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit VoltDc. + /// + /// Value assuming base unit VoltDc. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricPotentialDc(decimal voltsdc) - { - _voltsDc = Convert.ToDouble(voltsdc); - } + ElectricPotentialDc(decimal voltsdc) : this(Convert.ToDouble(voltsdc), BaseUnit) { } #region Properties @@ -119,64 +156,38 @@ public ElectricPotentialDc(double voltsdc) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricPotentialDcUnit BaseUnit - { - get { return ElectricPotentialDcUnit.VoltDc; } - } + public static ElectricPotentialDcUnit BaseUnit => ElectricPotentialDcUnit.VoltDc; /// /// All units of measurement for the ElectricPotentialDc quantity. /// public static ElectricPotentialDcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialDcUnit)).Cast().ToArray(); - /// /// Get ElectricPotentialDc in KilovoltsDc. /// - public double KilovoltsDc - { - get { return (_voltsDc) / 1e3d; } - } - + public double KilovoltsDc => As(ElectricPotentialDcUnit.KilovoltDc); /// /// Get ElectricPotentialDc in MegavoltsDc. /// - public double MegavoltsDc - { - get { return (_voltsDc) / 1e6d; } - } - + public double MegavoltsDc => As(ElectricPotentialDcUnit.MegavoltDc); /// /// Get ElectricPotentialDc in MicrovoltsDc. /// - public double MicrovoltsDc - { - get { return (_voltsDc) / 1e-6d; } - } - + public double MicrovoltsDc => As(ElectricPotentialDcUnit.MicrovoltDc); /// /// Get ElectricPotentialDc in MillivoltsDc. /// - public double MillivoltsDc - { - get { return (_voltsDc) / 1e-3d; } - } - + public double MillivoltsDc => As(ElectricPotentialDcUnit.MillivoltDc); /// /// Get ElectricPotentialDc in VoltsDc. /// - public double VoltsDc - { - get { return _voltsDc; } - } + public double VoltsDc => As(ElectricPotentialDcUnit.VoltDc); #endregion #region Static - public static ElectricPotentialDc Zero - { - get { return new ElectricPotentialDc(); } - } + public static ElectricPotentialDc Zero => new ElectricPotentialDc(0, BaseUnit); /// /// Get ElectricPotentialDc from KilovoltsDc. @@ -184,17 +195,13 @@ public static ElectricPotentialDc Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotentialDc FromKilovoltsDc(double kilovoltsdc) - { - double value = (double) kilovoltsdc; - return new ElectricPotentialDc((value) * 1e3d); - } #else public static ElectricPotentialDc FromKilovoltsDc(QuantityValue kilovoltsdc) +#endif { double value = (double) kilovoltsdc; - return new ElectricPotentialDc(((value) * 1e3d)); + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.KilovoltDc); } -#endif /// /// Get ElectricPotentialDc from MegavoltsDc. @@ -202,17 +209,13 @@ public static ElectricPotentialDc FromKilovoltsDc(QuantityValue kilovoltsdc) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotentialDc FromMegavoltsDc(double megavoltsdc) - { - double value = (double) megavoltsdc; - return new ElectricPotentialDc((value) * 1e6d); - } #else public static ElectricPotentialDc FromMegavoltsDc(QuantityValue megavoltsdc) +#endif { double value = (double) megavoltsdc; - return new ElectricPotentialDc(((value) * 1e6d)); + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MegavoltDc); } -#endif /// /// Get ElectricPotentialDc from MicrovoltsDc. @@ -220,17 +223,13 @@ public static ElectricPotentialDc FromMegavoltsDc(QuantityValue megavoltsdc) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotentialDc FromMicrovoltsDc(double microvoltsdc) - { - double value = (double) microvoltsdc; - return new ElectricPotentialDc((value) * 1e-6d); - } #else public static ElectricPotentialDc FromMicrovoltsDc(QuantityValue microvoltsdc) +#endif { double value = (double) microvoltsdc; - return new ElectricPotentialDc(((value) * 1e-6d)); + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MicrovoltDc); } -#endif /// /// Get ElectricPotentialDc from MillivoltsDc. @@ -238,17 +237,13 @@ public static ElectricPotentialDc FromMicrovoltsDc(QuantityValue microvoltsdc) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotentialDc FromMillivoltsDc(double millivoltsdc) - { - double value = (double) millivoltsdc; - return new ElectricPotentialDc((value) * 1e-3d); - } #else public static ElectricPotentialDc FromMillivoltsDc(QuantityValue millivoltsdc) +#endif { double value = (double) millivoltsdc; - return new ElectricPotentialDc(((value) * 1e-3d)); + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.MillivoltDc); } -#endif /// /// Get ElectricPotentialDc from VoltsDc. @@ -256,17 +251,13 @@ public static ElectricPotentialDc FromMillivoltsDc(QuantityValue millivoltsdc) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricPotentialDc FromVoltsDc(double voltsdc) - { - double value = (double) voltsdc; - return new ElectricPotentialDc(value); - } #else public static ElectricPotentialDc FromVoltsDc(QuantityValue voltsdc) +#endif { double value = (double) voltsdc; - return new ElectricPotentialDc((value)); + return new ElectricPotentialDc(value, ElectricPotentialDcUnit.VoltDc); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -361,22 +352,7 @@ public static ElectricPotentialDc From(double value, ElectricPotentialDcUnit fro public static ElectricPotentialDc From(QuantityValue value, ElectricPotentialDcUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricPotentialDcUnit.KilovoltDc: - return FromKilovoltsDc(value); - case ElectricPotentialDcUnit.MegavoltDc: - return FromMegavoltsDc(value); - case ElectricPotentialDcUnit.MicrovoltDc: - return FromMicrovoltsDc(value); - case ElectricPotentialDcUnit.MillivoltDc: - return FromMillivoltsDc(value); - case ElectricPotentialDcUnit.VoltDc: - return FromVoltsDc(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricPotentialDc((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -393,22 +369,8 @@ public static ElectricPotentialDc From(QuantityValue value, ElectricPotentialDcU { return null; } - switch (fromUnit) - { - case ElectricPotentialDcUnit.KilovoltDc: - return FromKilovoltsDc(value.Value); - case ElectricPotentialDcUnit.MegavoltDc: - return FromMegavoltsDc(value.Value); - case ElectricPotentialDcUnit.MicrovoltDc: - return FromMicrovoltsDc(value.Value); - case ElectricPotentialDcUnit.MillivoltDc: - return FromMillivoltsDc(value.Value); - case ElectricPotentialDcUnit.VoltDc: - return FromVoltsDc(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricPotentialDc((double)value.Value, fromUnit); } #endif @@ -427,12 +389,29 @@ public static string GetAbbreviation(ElectricPotentialDcUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricPotentialDcUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricPotentialDcUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -443,37 +422,37 @@ public static string GetAbbreviation(ElectricPotentialDcUnit unit, [CanBeNull] C #if !WINDOWS_UWP public static ElectricPotentialDc operator -(ElectricPotentialDc right) { - return new ElectricPotentialDc(-right._voltsDc); + return new ElectricPotentialDc(-right.Value, right.Unit); } public static ElectricPotentialDc operator +(ElectricPotentialDc left, ElectricPotentialDc right) { - return new ElectricPotentialDc(left._voltsDc + right._voltsDc); + return new ElectricPotentialDc(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricPotentialDc operator -(ElectricPotentialDc left, ElectricPotentialDc right) { - return new ElectricPotentialDc(left._voltsDc - right._voltsDc); + return new ElectricPotentialDc(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricPotentialDc operator *(double left, ElectricPotentialDc right) { - return new ElectricPotentialDc(left*right._voltsDc); + return new ElectricPotentialDc(left * right.Value, right.Unit); } public static ElectricPotentialDc operator *(ElectricPotentialDc left, double right) { - return new ElectricPotentialDc(left._voltsDc*(double)right); + return new ElectricPotentialDc(left.Value * right, left.Unit); } public static ElectricPotentialDc operator /(ElectricPotentialDc left, double right) { - return new ElectricPotentialDc(left._voltsDc/(double)right); + return new ElectricPotentialDc(left.Value / right, left.Unit); } public static double operator /(ElectricPotentialDc left, ElectricPotentialDc right) { - return Convert.ToDouble(left._voltsDc/right._voltsDc); + return left.VoltsDc / right.VoltsDc; } #endif @@ -496,43 +475,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricPotentialDc other) { - return _voltsDc.CompareTo(other._voltsDc); + return AsBaseUnitVoltsDc().CompareTo(other.AsBaseUnitVoltsDc()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricPotentialDc left, ElectricPotentialDc right) { - return left._voltsDc <= right._voltsDc; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricPotentialDc left, ElectricPotentialDc right) { - return left._voltsDc >= right._voltsDc; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricPotentialDc left, ElectricPotentialDc right) { - return left._voltsDc < right._voltsDc; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricPotentialDc left, ElectricPotentialDc right) { - return left._voltsDc > right._voltsDc; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricPotentialDc left, ElectricPotentialDc right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltsDc == right._voltsDc; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricPotentialDc left, ElectricPotentialDc right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltsDc != right._voltsDc; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -544,7 +523,7 @@ public override bool Equals(object obj) return false; } - return _voltsDc.Equals(((ElectricPotentialDc) obj)._voltsDc); + return AsBaseUnitVoltsDc().Equals(((ElectricPotentialDc) obj).AsBaseUnitVoltsDc()); } /// @@ -557,12 +536,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricPotentialDc other, ElectricPotentialDc maxError) { - return Math.Abs(_voltsDc - other._voltsDc) <= maxError._voltsDc; + return Math.Abs(AsBaseUnitVoltsDc() - other.AsBaseUnitVoltsDc()) <= maxError.AsBaseUnitVoltsDc(); } public override int GetHashCode() { - return _voltsDc.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -572,22 +551,23 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricPotentialDcUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitVoltsDc(); + switch (unit) { - case ElectricPotentialDcUnit.KilovoltDc: - return KilovoltsDc; - case ElectricPotentialDcUnit.MegavoltDc: - return MegavoltsDc; - case ElectricPotentialDcUnit.MicrovoltDc: - return MicrovoltsDc; - case ElectricPotentialDcUnit.MillivoltDc: - return MillivoltsDc; - case ElectricPotentialDcUnit.VoltDc: - return VoltsDc; + case ElectricPotentialDcUnit.KilovoltDc: return (baseUnitValue) / 1e3d; + case ElectricPotentialDcUnit.MegavoltDc: return (baseUnitValue) / 1e6d; + case ElectricPotentialDcUnit.MicrovoltDc: return (baseUnitValue) / 1e-6d; + case ElectricPotentialDcUnit.MillivoltDc: return (baseUnitValue) / 1e-3d; + case ElectricPotentialDcUnit.VoltDc: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -629,7 +609,11 @@ public static ElectricPotentialDc Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -648,17 +632,24 @@ public static ElectricPotentialDc Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricPotentialDc Parse(string str, [CanBeNull] Culture culture) + public static ElectricPotentialDc Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -684,16 +675,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricPotentialDc resu /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricPotentialDc result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricPotentialDc result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -706,6 +722,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -719,11 +736,14 @@ public static ElectricPotentialDcUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricPotentialDcUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -732,6 +752,8 @@ public static ElectricPotentialDcUnit ParseUnit(string str, [CanBeNull] string c /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -744,18 +766,18 @@ public static ElectricPotentialDcUnit ParseUnit(string str, [CanBeNull] string c #else public #endif - static ElectricPotentialDcUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricPotentialDcUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricPotentialDcUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricPotentialDcUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -764,6 +786,7 @@ static ElectricPotentialDcUnit ParseUnit(string str, IFormatProvider formatProvi #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is VoltDc /// @@ -775,7 +798,7 @@ static ElectricPotentialDcUnit ParseUnit(string str, IFormatProvider formatProvi /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -792,74 +815,133 @@ public string ToString(ElectricPotentialDcUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricPotentialDcUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricPotentialDcUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricPotentialDcUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricPotentialDcUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricPotentialDcUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricPotentialDcUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricPotentialDc /// - public static ElectricPotentialDc MaxValue - { - get - { - return new ElectricPotentialDc(double.MaxValue); - } - } + public static ElectricPotentialDc MaxValue => new ElectricPotentialDc(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricPotentialDc /// - public static ElectricPotentialDc MinValue + public static ElectricPotentialDc MinValue => new ElectricPotentialDc(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitVoltsDc() { - get + if (Unit == ElectricPotentialDcUnit.VoltDc) { return _value; } + + switch (Unit) { - return new ElectricPotentialDc(double.MinValue); - } - } - } + case ElectricPotentialDcUnit.KilovoltDc: return (_value) * 1e3d; + case ElectricPotentialDcUnit.MegavoltDc: return (_value) * 1e6d; + case ElectricPotentialDcUnit.MicrovoltDc: return (_value) * 1e-6d; + case ElectricPotentialDcUnit.MillivoltDc: return (_value) * 1e-3d; + case ElectricPotentialDcUnit.VoltDc: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricPotentialDcUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs index 6f2b01fce7..c9a6ca9c2b 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricResistance : IComparable, IComparable - /// Base unit of ElectricResistance. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _ohms; + private readonly ElectricResistanceUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricResistance() : this(0) + public ElectricResistance() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricResistance(double ohms) { - _ohms = Convert.ToDouble(ohms); + _value = Convert.ToDouble(ohms); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricResistance(double numericValue, ElectricResistanceUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Ohm. + /// + /// Value assuming base unit Ohm. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricResistance(long ohms) - { - _ohms = Convert.ToDouble(ohms); - } + ElectricResistance(long ohms) : this(Convert.ToDouble(ohms), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Ohm. + /// + /// Value assuming base unit Ohm. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricResistance(decimal ohms) - { - _ohms = Convert.ToDouble(ohms); - } + ElectricResistance(decimal ohms) : this(Convert.ToDouble(ohms), BaseUnit) { } #region Properties @@ -119,56 +156,34 @@ public ElectricResistance(double ohms) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricResistanceUnit BaseUnit - { - get { return ElectricResistanceUnit.Ohm; } - } + public static ElectricResistanceUnit BaseUnit => ElectricResistanceUnit.Ohm; /// /// All units of measurement for the ElectricResistance quantity. /// public static ElectricResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().ToArray(); - /// /// Get ElectricResistance in Kiloohms. /// - public double Kiloohms - { - get { return (_ohms) / 1e3d; } - } - + public double Kiloohms => As(ElectricResistanceUnit.Kiloohm); /// /// Get ElectricResistance in Megaohms. /// - public double Megaohms - { - get { return (_ohms) / 1e6d; } - } - + public double Megaohms => As(ElectricResistanceUnit.Megaohm); /// /// Get ElectricResistance in Milliohms. /// - public double Milliohms - { - get { return (_ohms) / 1e-3d; } - } - + public double Milliohms => As(ElectricResistanceUnit.Milliohm); /// /// Get ElectricResistance in Ohms. /// - public double Ohms - { - get { return _ohms; } - } + public double Ohms => As(ElectricResistanceUnit.Ohm); #endregion #region Static - public static ElectricResistance Zero - { - get { return new ElectricResistance(); } - } + public static ElectricResistance Zero => new ElectricResistance(0, BaseUnit); /// /// Get ElectricResistance from Kiloohms. @@ -176,17 +191,13 @@ public static ElectricResistance Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricResistance FromKiloohms(double kiloohms) - { - double value = (double) kiloohms; - return new ElectricResistance((value) * 1e3d); - } #else public static ElectricResistance FromKiloohms(QuantityValue kiloohms) +#endif { double value = (double) kiloohms; - return new ElectricResistance(((value) * 1e3d)); + return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); } -#endif /// /// Get ElectricResistance from Megaohms. @@ -194,17 +205,13 @@ public static ElectricResistance FromKiloohms(QuantityValue kiloohms) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricResistance FromMegaohms(double megaohms) - { - double value = (double) megaohms; - return new ElectricResistance((value) * 1e6d); - } #else public static ElectricResistance FromMegaohms(QuantityValue megaohms) +#endif { double value = (double) megaohms; - return new ElectricResistance(((value) * 1e6d)); + return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); } -#endif /// /// Get ElectricResistance from Milliohms. @@ -212,17 +219,13 @@ public static ElectricResistance FromMegaohms(QuantityValue megaohms) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricResistance FromMilliohms(double milliohms) - { - double value = (double) milliohms; - return new ElectricResistance((value) * 1e-3d); - } #else public static ElectricResistance FromMilliohms(QuantityValue milliohms) +#endif { double value = (double) milliohms; - return new ElectricResistance(((value) * 1e-3d)); + return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); } -#endif /// /// Get ElectricResistance from Ohms. @@ -230,17 +233,13 @@ public static ElectricResistance FromMilliohms(QuantityValue milliohms) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricResistance FromOhms(double ohms) - { - double value = (double) ohms; - return new ElectricResistance(value); - } #else public static ElectricResistance FromOhms(QuantityValue ohms) +#endif { double value = (double) ohms; - return new ElectricResistance((value)); + return new ElectricResistance(value, ElectricResistanceUnit.Ohm); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -320,20 +319,7 @@ public static ElectricResistance From(double value, ElectricResistanceUnit fromU public static ElectricResistance From(QuantityValue value, ElectricResistanceUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricResistanceUnit.Kiloohm: - return FromKiloohms(value); - case ElectricResistanceUnit.Megaohm: - return FromMegaohms(value); - case ElectricResistanceUnit.Milliohm: - return FromMilliohms(value); - case ElectricResistanceUnit.Ohm: - return FromOhms(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricResistance((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -350,20 +336,8 @@ public static ElectricResistance From(QuantityValue value, ElectricResistanceUni { return null; } - switch (fromUnit) - { - case ElectricResistanceUnit.Kiloohm: - return FromKiloohms(value.Value); - case ElectricResistanceUnit.Megaohm: - return FromMegaohms(value.Value); - case ElectricResistanceUnit.Milliohm: - return FromMilliohms(value.Value); - case ElectricResistanceUnit.Ohm: - return FromOhms(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricResistance((double)value.Value, fromUnit); } #endif @@ -382,12 +356,29 @@ public static string GetAbbreviation(ElectricResistanceUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricResistanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -398,37 +389,37 @@ public static string GetAbbreviation(ElectricResistanceUnit unit, [CanBeNull] Cu #if !WINDOWS_UWP public static ElectricResistance operator -(ElectricResistance right) { - return new ElectricResistance(-right._ohms); + return new ElectricResistance(-right.Value, right.Unit); } public static ElectricResistance operator +(ElectricResistance left, ElectricResistance right) { - return new ElectricResistance(left._ohms + right._ohms); + return new ElectricResistance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricResistance operator -(ElectricResistance left, ElectricResistance right) { - return new ElectricResistance(left._ohms - right._ohms); + return new ElectricResistance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricResistance operator *(double left, ElectricResistance right) { - return new ElectricResistance(left*right._ohms); + return new ElectricResistance(left * right.Value, right.Unit); } public static ElectricResistance operator *(ElectricResistance left, double right) { - return new ElectricResistance(left._ohms*(double)right); + return new ElectricResistance(left.Value * right, left.Unit); } public static ElectricResistance operator /(ElectricResistance left, double right) { - return new ElectricResistance(left._ohms/(double)right); + return new ElectricResistance(left.Value / right, left.Unit); } public static double operator /(ElectricResistance left, ElectricResistance right) { - return Convert.ToDouble(left._ohms/right._ohms); + return left.Ohms / right.Ohms; } #endif @@ -451,43 +442,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricResistance other) { - return _ohms.CompareTo(other._ohms); + return AsBaseUnitOhms().CompareTo(other.AsBaseUnitOhms()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricResistance left, ElectricResistance right) { - return left._ohms <= right._ohms; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricResistance left, ElectricResistance right) { - return left._ohms >= right._ohms; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricResistance left, ElectricResistance right) { - return left._ohms < right._ohms; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricResistance left, ElectricResistance right) { - return left._ohms > right._ohms; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricResistance left, ElectricResistance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._ohms == right._ohms; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricResistance left, ElectricResistance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._ohms != right._ohms; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -499,7 +490,7 @@ public override bool Equals(object obj) return false; } - return _ohms.Equals(((ElectricResistance) obj)._ohms); + return AsBaseUnitOhms().Equals(((ElectricResistance) obj).AsBaseUnitOhms()); } /// @@ -512,12 +503,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricResistance other, ElectricResistance maxError) { - return Math.Abs(_ohms - other._ohms) <= maxError._ohms; + return Math.Abs(AsBaseUnitOhms() - other.AsBaseUnitOhms()) <= maxError.AsBaseUnitOhms(); } public override int GetHashCode() { - return _ohms.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -527,20 +518,22 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricResistanceUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitOhms(); + switch (unit) { - case ElectricResistanceUnit.Kiloohm: - return Kiloohms; - case ElectricResistanceUnit.Megaohm: - return Megaohms; - case ElectricResistanceUnit.Milliohm: - return Milliohms; - case ElectricResistanceUnit.Ohm: - return Ohms; + case ElectricResistanceUnit.Kiloohm: return (baseUnitValue) / 1e3d; + case ElectricResistanceUnit.Megaohm: return (baseUnitValue) / 1e6d; + case ElectricResistanceUnit.Milliohm: return (baseUnitValue) / 1e-3d; + case ElectricResistanceUnit.Ohm: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -582,7 +575,11 @@ public static ElectricResistance Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -601,17 +598,24 @@ public static ElectricResistance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricResistance Parse(string str, [CanBeNull] Culture culture) + public static ElectricResistance Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -637,16 +641,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricResistance resul /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricResistance result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricResistance result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -659,6 +688,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -672,11 +702,14 @@ public static ElectricResistanceUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricResistanceUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -685,6 +718,8 @@ public static ElectricResistanceUnit ParseUnit(string str, [CanBeNull] string cu /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -697,18 +732,18 @@ public static ElectricResistanceUnit ParseUnit(string str, [CanBeNull] string cu #else public #endif - static ElectricResistanceUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricResistanceUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricResistanceUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricResistanceUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -717,6 +752,7 @@ static ElectricResistanceUnit ParseUnit(string str, IFormatProvider formatProvid #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Ohm /// @@ -728,7 +764,7 @@ static ElectricResistanceUnit ParseUnit(string str, IFormatProvider formatProvid /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -745,74 +781,132 @@ public string ToString(ElectricResistanceUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricResistanceUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricResistanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricResistanceUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricResistanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricResistanceUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricResistanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricResistance /// - public static ElectricResistance MaxValue - { - get - { - return new ElectricResistance(double.MaxValue); - } - } + public static ElectricResistance MaxValue => new ElectricResistance(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricResistance /// - public static ElectricResistance MinValue + public static ElectricResistance MinValue => new ElectricResistance(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitOhms() { - get + if (Unit == ElectricResistanceUnit.Ohm) { return _value; } + + switch (Unit) { - return new ElectricResistance(double.MinValue); - } - } - } + case ElectricResistanceUnit.Kiloohm: return (_value) * 1e3d; + case ElectricResistanceUnit.Megaohm: return (_value) * 1e6d; + case ElectricResistanceUnit.Milliohm: return (_value) * 1e-3d; + case ElectricResistanceUnit.Ohm: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricResistanceUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs index 4ea5354860..3392e3cec6 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ElectricResistivity : IComparable, IComparable - /// Base unit of ElectricResistivity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _ohmMeters; + private readonly ElectricResistivityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ElectricResistivity() : this(0) + public ElectricResistivity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ElectricResistivity(double ohmmeters) { - _ohmMeters = Convert.ToDouble(ohmmeters); + _value = Convert.ToDouble(ohmmeters); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ElectricResistivity(double numericValue, ElectricResistivityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit OhmMeter. + /// + /// Value assuming base unit OhmMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricResistivity(long ohmmeters) - { - _ohmMeters = Convert.ToDouble(ohmmeters); - } + ElectricResistivity(long ohmmeters) : this(Convert.ToDouble(ohmmeters), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit OhmMeter. + /// + /// Value assuming base unit OhmMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ElectricResistivity(decimal ohmmeters) - { - _ohmMeters = Convert.ToDouble(ohmmeters); - } + ElectricResistivity(decimal ohmmeters) : this(Convert.ToDouble(ohmmeters), BaseUnit) { } #region Properties @@ -119,56 +156,34 @@ public ElectricResistivity(double ohmmeters) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ElectricResistivityUnit BaseUnit - { - get { return ElectricResistivityUnit.OhmMeter; } - } + public static ElectricResistivityUnit BaseUnit => ElectricResistivityUnit.OhmMeter; /// /// All units of measurement for the ElectricResistivity quantity. /// public static ElectricResistivityUnit[] Units { get; } = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().ToArray(); - /// /// Get ElectricResistivity in MicroohmMeters. /// - public double MicroohmMeters - { - get { return (_ohmMeters) / 1e-6d; } - } - + public double MicroohmMeters => As(ElectricResistivityUnit.MicroohmMeter); /// /// Get ElectricResistivity in MilliohmMeters. /// - public double MilliohmMeters - { - get { return (_ohmMeters) / 1e-3d; } - } - + public double MilliohmMeters => As(ElectricResistivityUnit.MilliohmMeter); /// /// Get ElectricResistivity in NanoohmMeters. /// - public double NanoohmMeters - { - get { return (_ohmMeters) / 1e-9d; } - } - + public double NanoohmMeters => As(ElectricResistivityUnit.NanoohmMeter); /// /// Get ElectricResistivity in OhmMeters. /// - public double OhmMeters - { - get { return _ohmMeters; } - } + public double OhmMeters => As(ElectricResistivityUnit.OhmMeter); #endregion #region Static - public static ElectricResistivity Zero - { - get { return new ElectricResistivity(); } - } + public static ElectricResistivity Zero => new ElectricResistivity(0, BaseUnit); /// /// Get ElectricResistivity from MicroohmMeters. @@ -176,17 +191,13 @@ public static ElectricResistivity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricResistivity FromMicroohmMeters(double microohmmeters) - { - double value = (double) microohmmeters; - return new ElectricResistivity((value) * 1e-6d); - } #else public static ElectricResistivity FromMicroohmMeters(QuantityValue microohmmeters) +#endif { double value = (double) microohmmeters; - return new ElectricResistivity(((value) * 1e-6d)); + return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); } -#endif /// /// Get ElectricResistivity from MilliohmMeters. @@ -194,17 +205,13 @@ public static ElectricResistivity FromMicroohmMeters(QuantityValue microohmmeter #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricResistivity FromMilliohmMeters(double milliohmmeters) - { - double value = (double) milliohmmeters; - return new ElectricResistivity((value) * 1e-3d); - } #else public static ElectricResistivity FromMilliohmMeters(QuantityValue milliohmmeters) +#endif { double value = (double) milliohmmeters; - return new ElectricResistivity(((value) * 1e-3d)); + return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); } -#endif /// /// Get ElectricResistivity from NanoohmMeters. @@ -212,17 +219,13 @@ public static ElectricResistivity FromMilliohmMeters(QuantityValue milliohmmeter #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricResistivity FromNanoohmMeters(double nanoohmmeters) - { - double value = (double) nanoohmmeters; - return new ElectricResistivity((value) * 1e-9d); - } #else public static ElectricResistivity FromNanoohmMeters(QuantityValue nanoohmmeters) +#endif { double value = (double) nanoohmmeters; - return new ElectricResistivity(((value) * 1e-9d)); + return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); } -#endif /// /// Get ElectricResistivity from OhmMeters. @@ -230,17 +233,13 @@ public static ElectricResistivity FromNanoohmMeters(QuantityValue nanoohmmeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ElectricResistivity FromOhmMeters(double ohmmeters) - { - double value = (double) ohmmeters; - return new ElectricResistivity(value); - } #else public static ElectricResistivity FromOhmMeters(QuantityValue ohmmeters) +#endif { double value = (double) ohmmeters; - return new ElectricResistivity((value)); + return new ElectricResistivity(value, ElectricResistivityUnit.OhmMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -320,20 +319,7 @@ public static ElectricResistivity From(double value, ElectricResistivityUnit fro public static ElectricResistivity From(QuantityValue value, ElectricResistivityUnit fromUnit) #endif { - switch (fromUnit) - { - case ElectricResistivityUnit.MicroohmMeter: - return FromMicroohmMeters(value); - case ElectricResistivityUnit.MilliohmMeter: - return FromMilliohmMeters(value); - case ElectricResistivityUnit.NanoohmMeter: - return FromNanoohmMeters(value); - case ElectricResistivityUnit.OhmMeter: - return FromOhmMeters(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricResistivity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -350,20 +336,8 @@ public static ElectricResistivity From(QuantityValue value, ElectricResistivityU { return null; } - switch (fromUnit) - { - case ElectricResistivityUnit.MicroohmMeter: - return FromMicroohmMeters(value.Value); - case ElectricResistivityUnit.MilliohmMeter: - return FromMilliohmMeters(value.Value); - case ElectricResistivityUnit.NanoohmMeter: - return FromNanoohmMeters(value.Value); - case ElectricResistivityUnit.OhmMeter: - return FromOhmMeters(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ElectricResistivity((double)value.Value, fromUnit); } #endif @@ -382,12 +356,29 @@ public static string GetAbbreviation(ElectricResistivityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ElectricResistivityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ElectricResistivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -398,37 +389,37 @@ public static string GetAbbreviation(ElectricResistivityUnit unit, [CanBeNull] C #if !WINDOWS_UWP public static ElectricResistivity operator -(ElectricResistivity right) { - return new ElectricResistivity(-right._ohmMeters); + return new ElectricResistivity(-right.Value, right.Unit); } public static ElectricResistivity operator +(ElectricResistivity left, ElectricResistivity right) { - return new ElectricResistivity(left._ohmMeters + right._ohmMeters); + return new ElectricResistivity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricResistivity operator -(ElectricResistivity left, ElectricResistivity right) { - return new ElectricResistivity(left._ohmMeters - right._ohmMeters); + return new ElectricResistivity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ElectricResistivity operator *(double left, ElectricResistivity right) { - return new ElectricResistivity(left*right._ohmMeters); + return new ElectricResistivity(left * right.Value, right.Unit); } public static ElectricResistivity operator *(ElectricResistivity left, double right) { - return new ElectricResistivity(left._ohmMeters*(double)right); + return new ElectricResistivity(left.Value * right, left.Unit); } public static ElectricResistivity operator /(ElectricResistivity left, double right) { - return new ElectricResistivity(left._ohmMeters/(double)right); + return new ElectricResistivity(left.Value / right, left.Unit); } public static double operator /(ElectricResistivity left, ElectricResistivity right) { - return Convert.ToDouble(left._ohmMeters/right._ohmMeters); + return left.OhmMeters / right.OhmMeters; } #endif @@ -451,43 +442,43 @@ public int CompareTo(object obj) #endif int CompareTo(ElectricResistivity other) { - return _ohmMeters.CompareTo(other._ohmMeters); + return AsBaseUnitOhmMeters().CompareTo(other.AsBaseUnitOhmMeters()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ElectricResistivity left, ElectricResistivity right) { - return left._ohmMeters <= right._ohmMeters; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ElectricResistivity left, ElectricResistivity right) { - return left._ohmMeters >= right._ohmMeters; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ElectricResistivity left, ElectricResistivity right) { - return left._ohmMeters < right._ohmMeters; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ElectricResistivity left, ElectricResistivity right) { - return left._ohmMeters > right._ohmMeters; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ElectricResistivity left, ElectricResistivity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._ohmMeters == right._ohmMeters; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ElectricResistivity left, ElectricResistivity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._ohmMeters != right._ohmMeters; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -499,7 +490,7 @@ public override bool Equals(object obj) return false; } - return _ohmMeters.Equals(((ElectricResistivity) obj)._ohmMeters); + return AsBaseUnitOhmMeters().Equals(((ElectricResistivity) obj).AsBaseUnitOhmMeters()); } /// @@ -512,12 +503,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ElectricResistivity other, ElectricResistivity maxError) { - return Math.Abs(_ohmMeters - other._ohmMeters) <= maxError._ohmMeters; + return Math.Abs(AsBaseUnitOhmMeters() - other.AsBaseUnitOhmMeters()) <= maxError.AsBaseUnitOhmMeters(); } public override int GetHashCode() { - return _ohmMeters.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -527,20 +518,22 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ElectricResistivityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitOhmMeters(); + switch (unit) { - case ElectricResistivityUnit.MicroohmMeter: - return MicroohmMeters; - case ElectricResistivityUnit.MilliohmMeter: - return MilliohmMeters; - case ElectricResistivityUnit.NanoohmMeter: - return NanoohmMeters; - case ElectricResistivityUnit.OhmMeter: - return OhmMeters; + case ElectricResistivityUnit.MicroohmMeter: return (baseUnitValue) / 1e-6d; + case ElectricResistivityUnit.MilliohmMeter: return (baseUnitValue) / 1e-3d; + case ElectricResistivityUnit.NanoohmMeter: return (baseUnitValue) / 1e-9d; + case ElectricResistivityUnit.OhmMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -582,7 +575,11 @@ public static ElectricResistivity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -601,17 +598,24 @@ public static ElectricResistivity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ElectricResistivity Parse(string str, [CanBeNull] Culture culture) + public static ElectricResistivity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -637,16 +641,41 @@ public static bool TryParse([CanBeNull] string str, out ElectricResistivity resu /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ElectricResistivity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ElectricResistivity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -659,6 +688,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -672,11 +702,14 @@ public static ElectricResistivityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ElectricResistivityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -685,6 +718,8 @@ public static ElectricResistivityUnit ParseUnit(string str, [CanBeNull] string c /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -697,18 +732,18 @@ public static ElectricResistivityUnit ParseUnit(string str, [CanBeNull] string c #else public #endif - static ElectricResistivityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ElectricResistivityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ElectricResistivityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ElectricResistivityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -717,6 +752,7 @@ static ElectricResistivityUnit ParseUnit(string str, IFormatProvider formatProvi #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is OhmMeter /// @@ -728,7 +764,7 @@ static ElectricResistivityUnit ParseUnit(string str, IFormatProvider formatProvi /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -745,74 +781,132 @@ public string ToString(ElectricResistivityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ElectricResistivityUnit unit, [CanBeNull] Culture culture) + public string ToString( + ElectricResistivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ElectricResistivityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ElectricResistivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ElectricResistivityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ElectricResistivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ElectricResistivity /// - public static ElectricResistivity MaxValue - { - get - { - return new ElectricResistivity(double.MaxValue); - } - } + public static ElectricResistivity MaxValue => new ElectricResistivity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ElectricResistivity /// - public static ElectricResistivity MinValue + public static ElectricResistivity MinValue => new ElectricResistivity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitOhmMeters() { - get + if (Unit == ElectricResistivityUnit.OhmMeter) { return _value; } + + switch (Unit) { - return new ElectricResistivity(double.MinValue); - } - } - } + case ElectricResistivityUnit.MicroohmMeter: return (_value) * 1e-6d; + case ElectricResistivityUnit.MilliohmMeter: return (_value) * 1e-3d; + case ElectricResistivityUnit.NanoohmMeter: return (_value) * 1e-9d; + case ElectricResistivityUnit.OhmMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ElectricResistivityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs index ec7f9bc33c..3acb91a2e4 100644 --- a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Energy : IComparable, IComparable #endif { /// - /// Base unit of Energy. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _joules; + private readonly EnergyUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Energy() : this(0) + public Energy() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Energy(double joules) { - _joules = Convert.ToDouble(joules); + _value = Convert.ToDouble(joules); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Energy(double numericValue, EnergyUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Joule. + /// + /// Value assuming base unit Joule. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Energy(long joules) - { - _joules = Convert.ToDouble(joules); - } + Energy(long joules) : this(Convert.ToDouble(joules), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Joule. + /// + /// Value assuming base unit Joule. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Energy(decimal joules) - { - _joules = Convert.ToDouble(joules); - } + Energy(decimal joules) : this(Convert.ToDouble(joules), BaseUnit) { } #region Properties @@ -119,200 +156,106 @@ public Energy(double joules) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static EnergyUnit BaseUnit - { - get { return EnergyUnit.Joule; } - } + public static EnergyUnit BaseUnit => EnergyUnit.Joule; /// /// All units of measurement for the Energy quantity. /// public static EnergyUnit[] Units { get; } = Enum.GetValues(typeof(EnergyUnit)).Cast().ToArray(); - /// /// Get Energy in BritishThermalUnits. /// - public double BritishThermalUnits - { - get { return _joules/1055.05585262; } - } - + public double BritishThermalUnits => As(EnergyUnit.BritishThermalUnit); /// /// Get Energy in Calories. /// - public double Calories - { - get { return _joules/4.184; } - } - + public double Calories => As(EnergyUnit.Calorie); /// /// Get Energy in DecathermsEc. /// - public double DecathermsEc - { - get { return (_joules/105505585.262) / 1e1d; } - } - + public double DecathermsEc => As(EnergyUnit.DecathermEc); /// /// Get Energy in DecathermsImperial. /// - public double DecathermsImperial - { - get { return (_joules/1.05505585257348e+14) / 1e1d; } - } - + public double DecathermsImperial => As(EnergyUnit.DecathermImperial); /// /// Get Energy in DecathermsUs. /// - public double DecathermsUs - { - get { return (_joules/1.054804e+8) / 1e1d; } - } - + public double DecathermsUs => As(EnergyUnit.DecathermUs); /// /// Get Energy in ElectronVolts. /// - public double ElectronVolts - { - get { return _joules/1.602176565e-19; } - } - + public double ElectronVolts => As(EnergyUnit.ElectronVolt); /// /// Get Energy in Ergs. /// - public double Ergs - { - get { return _joules/1e-7; } - } - + public double Ergs => As(EnergyUnit.Erg); /// /// Get Energy in FootPounds. /// - public double FootPounds - { - get { return _joules/1.355817948; } - } - + public double FootPounds => As(EnergyUnit.FootPound); /// /// Get Energy in GigabritishThermalUnits. /// - public double GigabritishThermalUnits - { - get { return (_joules/1055.05585262) / 1e9d; } - } - + public double GigabritishThermalUnits => As(EnergyUnit.GigabritishThermalUnit); /// /// Get Energy in GigawattHours. /// - public double GigawattHours - { - get { return (_joules/3600d) / 1e9d; } - } - + public double GigawattHours => As(EnergyUnit.GigawattHour); /// /// Get Energy in Joules. /// - public double Joules - { - get { return _joules; } - } - + public double Joules => As(EnergyUnit.Joule); /// /// Get Energy in KilobritishThermalUnits. /// - public double KilobritishThermalUnits - { - get { return (_joules/1055.05585262) / 1e3d; } - } - + public double KilobritishThermalUnits => As(EnergyUnit.KilobritishThermalUnit); /// /// Get Energy in Kilocalories. /// - public double Kilocalories - { - get { return (_joules/4.184) / 1e3d; } - } - + public double Kilocalories => As(EnergyUnit.Kilocalorie); /// /// Get Energy in Kilojoules. /// - public double Kilojoules - { - get { return (_joules) / 1e3d; } - } - + public double Kilojoules => As(EnergyUnit.Kilojoule); /// /// Get Energy in KilowattHours. /// - public double KilowattHours - { - get { return (_joules/3600d) / 1e3d; } - } - + public double KilowattHours => As(EnergyUnit.KilowattHour); /// /// Get Energy in MegabritishThermalUnits. /// - public double MegabritishThermalUnits - { - get { return (_joules/1055.05585262) / 1e6d; } - } - + public double MegabritishThermalUnits => As(EnergyUnit.MegabritishThermalUnit); /// /// Get Energy in Megajoules. /// - public double Megajoules - { - get { return (_joules) / 1e6d; } - } - + public double Megajoules => As(EnergyUnit.Megajoule); /// /// Get Energy in MegawattHours. /// - public double MegawattHours - { - get { return (_joules/3600d) / 1e6d; } - } - + public double MegawattHours => As(EnergyUnit.MegawattHour); /// /// Get Energy in ThermsEc. /// - public double ThermsEc - { - get { return _joules/105505585.262; } - } - + public double ThermsEc => As(EnergyUnit.ThermEc); /// /// Get Energy in ThermsImperial. /// - public double ThermsImperial - { - get { return _joules/1.05505585257348e+14; } - } - + public double ThermsImperial => As(EnergyUnit.ThermImperial); /// /// Get Energy in ThermsUs. /// - public double ThermsUs - { - get { return _joules/1.054804e+8; } - } - + public double ThermsUs => As(EnergyUnit.ThermUs); /// /// Get Energy in WattHours. /// - public double WattHours - { - get { return _joules/3600d; } - } + public double WattHours => As(EnergyUnit.WattHour); #endregion #region Static - public static Energy Zero - { - get { return new Energy(); } - } + public static Energy Zero => new Energy(0, BaseUnit); /// /// Get Energy from BritishThermalUnits. @@ -320,17 +263,13 @@ public static Energy Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromBritishThermalUnits(double britishthermalunits) - { - double value = (double) britishthermalunits; - return new Energy(value*1055.05585262); - } #else public static Energy FromBritishThermalUnits(QuantityValue britishthermalunits) +#endif { double value = (double) britishthermalunits; - return new Energy((value*1055.05585262)); + return new Energy(value, EnergyUnit.BritishThermalUnit); } -#endif /// /// Get Energy from Calories. @@ -338,17 +277,13 @@ public static Energy FromBritishThermalUnits(QuantityValue britishthermalunits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromCalories(double calories) - { - double value = (double) calories; - return new Energy(value*4.184); - } #else public static Energy FromCalories(QuantityValue calories) +#endif { double value = (double) calories; - return new Energy((value*4.184)); + return new Energy(value, EnergyUnit.Calorie); } -#endif /// /// Get Energy from DecathermsEc. @@ -356,17 +291,13 @@ public static Energy FromCalories(QuantityValue calories) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromDecathermsEc(double decathermsec) - { - double value = (double) decathermsec; - return new Energy((value*105505585.262) * 1e1d); - } #else public static Energy FromDecathermsEc(QuantityValue decathermsec) +#endif { double value = (double) decathermsec; - return new Energy(((value*105505585.262) * 1e1d)); + return new Energy(value, EnergyUnit.DecathermEc); } -#endif /// /// Get Energy from DecathermsImperial. @@ -374,17 +305,13 @@ public static Energy FromDecathermsEc(QuantityValue decathermsec) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromDecathermsImperial(double decathermsimperial) - { - double value = (double) decathermsimperial; - return new Energy((value*1.05505585257348e+14) * 1e1d); - } #else public static Energy FromDecathermsImperial(QuantityValue decathermsimperial) +#endif { double value = (double) decathermsimperial; - return new Energy(((value*1.05505585257348e+14) * 1e1d)); + return new Energy(value, EnergyUnit.DecathermImperial); } -#endif /// /// Get Energy from DecathermsUs. @@ -392,17 +319,13 @@ public static Energy FromDecathermsImperial(QuantityValue decathermsimperial) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromDecathermsUs(double decathermsus) - { - double value = (double) decathermsus; - return new Energy((value*1.054804e+8) * 1e1d); - } #else public static Energy FromDecathermsUs(QuantityValue decathermsus) +#endif { double value = (double) decathermsus; - return new Energy(((value*1.054804e+8) * 1e1d)); + return new Energy(value, EnergyUnit.DecathermUs); } -#endif /// /// Get Energy from ElectronVolts. @@ -410,17 +333,13 @@ public static Energy FromDecathermsUs(QuantityValue decathermsus) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromElectronVolts(double electronvolts) - { - double value = (double) electronvolts; - return new Energy(value*1.602176565e-19); - } #else public static Energy FromElectronVolts(QuantityValue electronvolts) +#endif { double value = (double) electronvolts; - return new Energy((value*1.602176565e-19)); + return new Energy(value, EnergyUnit.ElectronVolt); } -#endif /// /// Get Energy from Ergs. @@ -428,17 +347,13 @@ public static Energy FromElectronVolts(QuantityValue electronvolts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromErgs(double ergs) - { - double value = (double) ergs; - return new Energy(value*1e-7); - } #else public static Energy FromErgs(QuantityValue ergs) +#endif { double value = (double) ergs; - return new Energy((value*1e-7)); + return new Energy(value, EnergyUnit.Erg); } -#endif /// /// Get Energy from FootPounds. @@ -446,17 +361,13 @@ public static Energy FromErgs(QuantityValue ergs) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromFootPounds(double footpounds) - { - double value = (double) footpounds; - return new Energy(value*1.355817948); - } #else public static Energy FromFootPounds(QuantityValue footpounds) +#endif { double value = (double) footpounds; - return new Energy((value*1.355817948)); + return new Energy(value, EnergyUnit.FootPound); } -#endif /// /// Get Energy from GigabritishThermalUnits. @@ -464,17 +375,13 @@ public static Energy FromFootPounds(QuantityValue footpounds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromGigabritishThermalUnits(double gigabritishthermalunits) - { - double value = (double) gigabritishthermalunits; - return new Energy((value*1055.05585262) * 1e9d); - } #else public static Energy FromGigabritishThermalUnits(QuantityValue gigabritishthermalunits) +#endif { double value = (double) gigabritishthermalunits; - return new Energy(((value*1055.05585262) * 1e9d)); + return new Energy(value, EnergyUnit.GigabritishThermalUnit); } -#endif /// /// Get Energy from GigawattHours. @@ -482,17 +389,13 @@ public static Energy FromGigabritishThermalUnits(QuantityValue gigabritishtherma #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromGigawattHours(double gigawatthours) - { - double value = (double) gigawatthours; - return new Energy((value*3600d) * 1e9d); - } #else public static Energy FromGigawattHours(QuantityValue gigawatthours) +#endif { double value = (double) gigawatthours; - return new Energy(((value*3600d) * 1e9d)); + return new Energy(value, EnergyUnit.GigawattHour); } -#endif /// /// Get Energy from Joules. @@ -500,17 +403,13 @@ public static Energy FromGigawattHours(QuantityValue gigawatthours) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromJoules(double joules) - { - double value = (double) joules; - return new Energy(value); - } #else public static Energy FromJoules(QuantityValue joules) +#endif { double value = (double) joules; - return new Energy((value)); + return new Energy(value, EnergyUnit.Joule); } -#endif /// /// Get Energy from KilobritishThermalUnits. @@ -518,17 +417,13 @@ public static Energy FromJoules(QuantityValue joules) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromKilobritishThermalUnits(double kilobritishthermalunits) - { - double value = (double) kilobritishthermalunits; - return new Energy((value*1055.05585262) * 1e3d); - } #else public static Energy FromKilobritishThermalUnits(QuantityValue kilobritishthermalunits) +#endif { double value = (double) kilobritishthermalunits; - return new Energy(((value*1055.05585262) * 1e3d)); + return new Energy(value, EnergyUnit.KilobritishThermalUnit); } -#endif /// /// Get Energy from Kilocalories. @@ -536,17 +431,13 @@ public static Energy FromKilobritishThermalUnits(QuantityValue kilobritishtherma #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromKilocalories(double kilocalories) - { - double value = (double) kilocalories; - return new Energy((value*4.184) * 1e3d); - } #else public static Energy FromKilocalories(QuantityValue kilocalories) +#endif { double value = (double) kilocalories; - return new Energy(((value*4.184) * 1e3d)); + return new Energy(value, EnergyUnit.Kilocalorie); } -#endif /// /// Get Energy from Kilojoules. @@ -554,17 +445,13 @@ public static Energy FromKilocalories(QuantityValue kilocalories) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromKilojoules(double kilojoules) - { - double value = (double) kilojoules; - return new Energy((value) * 1e3d); - } #else public static Energy FromKilojoules(QuantityValue kilojoules) +#endif { double value = (double) kilojoules; - return new Energy(((value) * 1e3d)); + return new Energy(value, EnergyUnit.Kilojoule); } -#endif /// /// Get Energy from KilowattHours. @@ -572,17 +459,13 @@ public static Energy FromKilojoules(QuantityValue kilojoules) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromKilowattHours(double kilowatthours) - { - double value = (double) kilowatthours; - return new Energy((value*3600d) * 1e3d); - } #else public static Energy FromKilowattHours(QuantityValue kilowatthours) +#endif { double value = (double) kilowatthours; - return new Energy(((value*3600d) * 1e3d)); + return new Energy(value, EnergyUnit.KilowattHour); } -#endif /// /// Get Energy from MegabritishThermalUnits. @@ -590,17 +473,13 @@ public static Energy FromKilowattHours(QuantityValue kilowatthours) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromMegabritishThermalUnits(double megabritishthermalunits) - { - double value = (double) megabritishthermalunits; - return new Energy((value*1055.05585262) * 1e6d); - } #else public static Energy FromMegabritishThermalUnits(QuantityValue megabritishthermalunits) +#endif { double value = (double) megabritishthermalunits; - return new Energy(((value*1055.05585262) * 1e6d)); + return new Energy(value, EnergyUnit.MegabritishThermalUnit); } -#endif /// /// Get Energy from Megajoules. @@ -608,17 +487,13 @@ public static Energy FromMegabritishThermalUnits(QuantityValue megabritishtherma #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromMegajoules(double megajoules) - { - double value = (double) megajoules; - return new Energy((value) * 1e6d); - } #else public static Energy FromMegajoules(QuantityValue megajoules) +#endif { double value = (double) megajoules; - return new Energy(((value) * 1e6d)); + return new Energy(value, EnergyUnit.Megajoule); } -#endif /// /// Get Energy from MegawattHours. @@ -626,17 +501,13 @@ public static Energy FromMegajoules(QuantityValue megajoules) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromMegawattHours(double megawatthours) - { - double value = (double) megawatthours; - return new Energy((value*3600d) * 1e6d); - } #else public static Energy FromMegawattHours(QuantityValue megawatthours) +#endif { double value = (double) megawatthours; - return new Energy(((value*3600d) * 1e6d)); + return new Energy(value, EnergyUnit.MegawattHour); } -#endif /// /// Get Energy from ThermsEc. @@ -644,17 +515,13 @@ public static Energy FromMegawattHours(QuantityValue megawatthours) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromThermsEc(double thermsec) - { - double value = (double) thermsec; - return new Energy(value*105505585.262); - } #else public static Energy FromThermsEc(QuantityValue thermsec) +#endif { double value = (double) thermsec; - return new Energy((value*105505585.262)); + return new Energy(value, EnergyUnit.ThermEc); } -#endif /// /// Get Energy from ThermsImperial. @@ -662,17 +529,13 @@ public static Energy FromThermsEc(QuantityValue thermsec) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromThermsImperial(double thermsimperial) - { - double value = (double) thermsimperial; - return new Energy(value*1.05505585257348e+14); - } #else public static Energy FromThermsImperial(QuantityValue thermsimperial) +#endif { double value = (double) thermsimperial; - return new Energy((value*1.05505585257348e+14)); + return new Energy(value, EnergyUnit.ThermImperial); } -#endif /// /// Get Energy from ThermsUs. @@ -680,17 +543,13 @@ public static Energy FromThermsImperial(QuantityValue thermsimperial) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromThermsUs(double thermsus) - { - double value = (double) thermsus; - return new Energy(value*1.054804e+8); - } #else public static Energy FromThermsUs(QuantityValue thermsus) +#endif { double value = (double) thermsus; - return new Energy((value*1.054804e+8)); + return new Energy(value, EnergyUnit.ThermUs); } -#endif /// /// Get Energy from WattHours. @@ -698,17 +557,13 @@ public static Energy FromThermsUs(QuantityValue thermsus) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Energy FromWattHours(double watthours) - { - double value = (double) watthours; - return new Energy(value*3600d); - } #else public static Energy FromWattHours(QuantityValue watthours) +#endif { double value = (double) watthours; - return new Energy((value*3600d)); + return new Energy(value, EnergyUnit.WattHour); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1058,56 +913,7 @@ public static Energy From(double value, EnergyUnit fromUnit) public static Energy From(QuantityValue value, EnergyUnit fromUnit) #endif { - switch (fromUnit) - { - case EnergyUnit.BritishThermalUnit: - return FromBritishThermalUnits(value); - case EnergyUnit.Calorie: - return FromCalories(value); - case EnergyUnit.DecathermEc: - return FromDecathermsEc(value); - case EnergyUnit.DecathermImperial: - return FromDecathermsImperial(value); - case EnergyUnit.DecathermUs: - return FromDecathermsUs(value); - case EnergyUnit.ElectronVolt: - return FromElectronVolts(value); - case EnergyUnit.Erg: - return FromErgs(value); - case EnergyUnit.FootPound: - return FromFootPounds(value); - case EnergyUnit.GigabritishThermalUnit: - return FromGigabritishThermalUnits(value); - case EnergyUnit.GigawattHour: - return FromGigawattHours(value); - case EnergyUnit.Joule: - return FromJoules(value); - case EnergyUnit.KilobritishThermalUnit: - return FromKilobritishThermalUnits(value); - case EnergyUnit.Kilocalorie: - return FromKilocalories(value); - case EnergyUnit.Kilojoule: - return FromKilojoules(value); - case EnergyUnit.KilowattHour: - return FromKilowattHours(value); - case EnergyUnit.MegabritishThermalUnit: - return FromMegabritishThermalUnits(value); - case EnergyUnit.Megajoule: - return FromMegajoules(value); - case EnergyUnit.MegawattHour: - return FromMegawattHours(value); - case EnergyUnit.ThermEc: - return FromThermsEc(value); - case EnergyUnit.ThermImperial: - return FromThermsImperial(value); - case EnergyUnit.ThermUs: - return FromThermsUs(value); - case EnergyUnit.WattHour: - return FromWattHours(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Energy((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1124,56 +930,8 @@ public static Energy From(QuantityValue value, EnergyUnit fromUnit) { return null; } - switch (fromUnit) - { - case EnergyUnit.BritishThermalUnit: - return FromBritishThermalUnits(value.Value); - case EnergyUnit.Calorie: - return FromCalories(value.Value); - case EnergyUnit.DecathermEc: - return FromDecathermsEc(value.Value); - case EnergyUnit.DecathermImperial: - return FromDecathermsImperial(value.Value); - case EnergyUnit.DecathermUs: - return FromDecathermsUs(value.Value); - case EnergyUnit.ElectronVolt: - return FromElectronVolts(value.Value); - case EnergyUnit.Erg: - return FromErgs(value.Value); - case EnergyUnit.FootPound: - return FromFootPounds(value.Value); - case EnergyUnit.GigabritishThermalUnit: - return FromGigabritishThermalUnits(value.Value); - case EnergyUnit.GigawattHour: - return FromGigawattHours(value.Value); - case EnergyUnit.Joule: - return FromJoules(value.Value); - case EnergyUnit.KilobritishThermalUnit: - return FromKilobritishThermalUnits(value.Value); - case EnergyUnit.Kilocalorie: - return FromKilocalories(value.Value); - case EnergyUnit.Kilojoule: - return FromKilojoules(value.Value); - case EnergyUnit.KilowattHour: - return FromKilowattHours(value.Value); - case EnergyUnit.MegabritishThermalUnit: - return FromMegabritishThermalUnits(value.Value); - case EnergyUnit.Megajoule: - return FromMegajoules(value.Value); - case EnergyUnit.MegawattHour: - return FromMegawattHours(value.Value); - case EnergyUnit.ThermEc: - return FromThermsEc(value.Value); - case EnergyUnit.ThermImperial: - return FromThermsImperial(value.Value); - case EnergyUnit.ThermUs: - return FromThermsUs(value.Value); - case EnergyUnit.WattHour: - return FromWattHours(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Energy((double)value.Value, fromUnit); } #endif @@ -1192,12 +950,29 @@ public static string GetAbbreviation(EnergyUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(EnergyUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + EnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1208,37 +983,37 @@ public static string GetAbbreviation(EnergyUnit unit, [CanBeNull] Culture cultur #if !WINDOWS_UWP public static Energy operator -(Energy right) { - return new Energy(-right._joules); + return new Energy(-right.Value, right.Unit); } public static Energy operator +(Energy left, Energy right) { - return new Energy(left._joules + right._joules); + return new Energy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Energy operator -(Energy left, Energy right) { - return new Energy(left._joules - right._joules); + return new Energy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Energy operator *(double left, Energy right) { - return new Energy(left*right._joules); + return new Energy(left * right.Value, right.Unit); } public static Energy operator *(Energy left, double right) { - return new Energy(left._joules*(double)right); + return new Energy(left.Value * right, left.Unit); } public static Energy operator /(Energy left, double right) { - return new Energy(left._joules/(double)right); + return new Energy(left.Value / right, left.Unit); } public static double operator /(Energy left, Energy right) { - return Convert.ToDouble(left._joules/right._joules); + return left.Joules / right.Joules; } #endif @@ -1261,43 +1036,43 @@ public int CompareTo(object obj) #endif int CompareTo(Energy other) { - return _joules.CompareTo(other._joules); + return AsBaseUnitJoules().CompareTo(other.AsBaseUnitJoules()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Energy left, Energy right) { - return left._joules <= right._joules; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Energy left, Energy right) { - return left._joules >= right._joules; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Energy left, Energy right) { - return left._joules < right._joules; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Energy left, Energy right) { - return left._joules > right._joules; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Energy left, Energy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joules == right._joules; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Energy left, Energy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joules != right._joules; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1309,7 +1084,7 @@ public override bool Equals(object obj) return false; } - return _joules.Equals(((Energy) obj)._joules); + return AsBaseUnitJoules().Equals(((Energy) obj).AsBaseUnitJoules()); } /// @@ -1322,12 +1097,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Energy other, Energy maxError) { - return Math.Abs(_joules - other._joules) <= maxError._joules; + return Math.Abs(AsBaseUnitJoules() - other.AsBaseUnitJoules()) <= maxError.AsBaseUnitJoules(); } public override int GetHashCode() { - return _joules.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1337,56 +1112,40 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(EnergyUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitJoules(); + switch (unit) { - case EnergyUnit.BritishThermalUnit: - return BritishThermalUnits; - case EnergyUnit.Calorie: - return Calories; - case EnergyUnit.DecathermEc: - return DecathermsEc; - case EnergyUnit.DecathermImperial: - return DecathermsImperial; - case EnergyUnit.DecathermUs: - return DecathermsUs; - case EnergyUnit.ElectronVolt: - return ElectronVolts; - case EnergyUnit.Erg: - return Ergs; - case EnergyUnit.FootPound: - return FootPounds; - case EnergyUnit.GigabritishThermalUnit: - return GigabritishThermalUnits; - case EnergyUnit.GigawattHour: - return GigawattHours; - case EnergyUnit.Joule: - return Joules; - case EnergyUnit.KilobritishThermalUnit: - return KilobritishThermalUnits; - case EnergyUnit.Kilocalorie: - return Kilocalories; - case EnergyUnit.Kilojoule: - return Kilojoules; - case EnergyUnit.KilowattHour: - return KilowattHours; - case EnergyUnit.MegabritishThermalUnit: - return MegabritishThermalUnits; - case EnergyUnit.Megajoule: - return Megajoules; - case EnergyUnit.MegawattHour: - return MegawattHours; - case EnergyUnit.ThermEc: - return ThermsEc; - case EnergyUnit.ThermImperial: - return ThermsImperial; - case EnergyUnit.ThermUs: - return ThermsUs; - case EnergyUnit.WattHour: - return WattHours; + case EnergyUnit.BritishThermalUnit: return baseUnitValue/1055.05585262; + case EnergyUnit.Calorie: return baseUnitValue/4.184; + case EnergyUnit.DecathermEc: return (baseUnitValue/105505585.262) / 1e1d; + case EnergyUnit.DecathermImperial: return (baseUnitValue/1.05505585257348e+14) / 1e1d; + case EnergyUnit.DecathermUs: return (baseUnitValue/1.054804e+8) / 1e1d; + case EnergyUnit.ElectronVolt: return baseUnitValue/1.602176565e-19; + case EnergyUnit.Erg: return baseUnitValue/1e-7; + case EnergyUnit.FootPound: return baseUnitValue/1.355817948; + case EnergyUnit.GigabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e9d; + case EnergyUnit.GigawattHour: return (baseUnitValue/3600d) / 1e9d; + case EnergyUnit.Joule: return baseUnitValue; + case EnergyUnit.KilobritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e3d; + case EnergyUnit.Kilocalorie: return (baseUnitValue/4.184) / 1e3d; + case EnergyUnit.Kilojoule: return (baseUnitValue) / 1e3d; + case EnergyUnit.KilowattHour: return (baseUnitValue/3600d) / 1e3d; + case EnergyUnit.MegabritishThermalUnit: return (baseUnitValue/1055.05585262) / 1e6d; + case EnergyUnit.Megajoule: return (baseUnitValue) / 1e6d; + case EnergyUnit.MegawattHour: return (baseUnitValue/3600d) / 1e6d; + case EnergyUnit.ThermEc: return baseUnitValue/105505585.262; + case EnergyUnit.ThermImperial: return baseUnitValue/1.05505585257348e+14; + case EnergyUnit.ThermUs: return baseUnitValue/1.054804e+8; + case EnergyUnit.WattHour: return baseUnitValue/3600d; default: throw new NotImplementedException("unit: " + unit); @@ -1428,7 +1187,11 @@ public static Energy Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1447,17 +1210,24 @@ public static Energy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Energy Parse(string str, [CanBeNull] Culture culture) + public static Energy Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1483,16 +1253,41 @@ public static bool TryParse([CanBeNull] string str, out Energy result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Energy result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Energy result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1505,6 +1300,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1518,11 +1314,14 @@ public static EnergyUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static EnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1531,6 +1330,8 @@ public static EnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1543,18 +1344,18 @@ public static EnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static EnergyUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static EnergyUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == EnergyUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized EnergyUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1563,6 +1364,7 @@ static EnergyUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Joule /// @@ -1574,7 +1376,7 @@ static EnergyUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1591,74 +1393,150 @@ public string ToString(EnergyUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(EnergyUnit unit, [CanBeNull] Culture culture) + public string ToString( + EnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(EnergyUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + EnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(EnergyUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + EnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Energy /// - public static Energy MaxValue - { - get - { - return new Energy(double.MaxValue); - } - } + public static Energy MaxValue => new Energy(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Energy /// - public static Energy MinValue + public static Energy MinValue => new Energy(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitJoules() { - get + if (Unit == EnergyUnit.Joule) { return _value; } + + switch (Unit) { - return new Energy(double.MinValue); - } - } - } + case EnergyUnit.BritishThermalUnit: return _value*1055.05585262; + case EnergyUnit.Calorie: return _value*4.184; + case EnergyUnit.DecathermEc: return (_value*105505585.262) * 1e1d; + case EnergyUnit.DecathermImperial: return (_value*1.05505585257348e+14) * 1e1d; + case EnergyUnit.DecathermUs: return (_value*1.054804e+8) * 1e1d; + case EnergyUnit.ElectronVolt: return _value*1.602176565e-19; + case EnergyUnit.Erg: return _value*1e-7; + case EnergyUnit.FootPound: return _value*1.355817948; + case EnergyUnit.GigabritishThermalUnit: return (_value*1055.05585262) * 1e9d; + case EnergyUnit.GigawattHour: return (_value*3600d) * 1e9d; + case EnergyUnit.Joule: return _value; + case EnergyUnit.KilobritishThermalUnit: return (_value*1055.05585262) * 1e3d; + case EnergyUnit.Kilocalorie: return (_value*4.184) * 1e3d; + case EnergyUnit.Kilojoule: return (_value) * 1e3d; + case EnergyUnit.KilowattHour: return (_value*3600d) * 1e3d; + case EnergyUnit.MegabritishThermalUnit: return (_value*1055.05585262) * 1e6d; + case EnergyUnit.Megajoule: return (_value) * 1e6d; + case EnergyUnit.MegawattHour: return (_value*3600d) * 1e6d; + case EnergyUnit.ThermEc: return _value*105505585.262; + case EnergyUnit.ThermImperial: return _value*1.05505585257348e+14; + case EnergyUnit.ThermUs: return _value*1.054804e+8; + case EnergyUnit.WattHour: return _value*3600d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(EnergyUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs index b484ffb54a..887e7fc75b 100644 --- a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Entropy : IComparable, IComparable #endif { /// - /// Base unit of Entropy. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly EntropyUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _joulesPerKelvin; + public EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Entropy() : this(0) + public Entropy() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Entropy(double joulesperkelvin) { - _joulesPerKelvin = Convert.ToDouble(joulesperkelvin); + _value = Convert.ToDouble(joulesperkelvin); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Entropy(double numericValue, EntropyUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit JoulePerKelvin. + /// + /// Value assuming base unit JoulePerKelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Entropy(long joulesperkelvin) - { - _joulesPerKelvin = Convert.ToDouble(joulesperkelvin); - } + Entropy(long joulesperkelvin) : this(Convert.ToDouble(joulesperkelvin), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit JoulePerKelvin. + /// + /// Value assuming base unit JoulePerKelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Entropy(decimal joulesperkelvin) - { - _joulesPerKelvin = Convert.ToDouble(joulesperkelvin); - } + Entropy(decimal joulesperkelvin) : this(Convert.ToDouble(joulesperkelvin), BaseUnit) { } #region Properties @@ -119,80 +156,46 @@ public Entropy(double joulesperkelvin) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static EntropyUnit BaseUnit - { - get { return EntropyUnit.JoulePerKelvin; } - } + public static EntropyUnit BaseUnit => EntropyUnit.JoulePerKelvin; /// /// All units of measurement for the Entropy quantity. /// public static EntropyUnit[] Units { get; } = Enum.GetValues(typeof(EntropyUnit)).Cast().ToArray(); - /// /// Get Entropy in CaloriesPerKelvin. /// - public double CaloriesPerKelvin - { - get { return _joulesPerKelvin/4.184; } - } - + public double CaloriesPerKelvin => As(EntropyUnit.CaloriePerKelvin); /// /// Get Entropy in JoulesPerDegreeCelsius. /// - public double JoulesPerDegreeCelsius - { - get { return _joulesPerKelvin; } - } - + public double JoulesPerDegreeCelsius => As(EntropyUnit.JoulePerDegreeCelsius); /// /// Get Entropy in JoulesPerKelvin. /// - public double JoulesPerKelvin - { - get { return _joulesPerKelvin; } - } - + public double JoulesPerKelvin => As(EntropyUnit.JoulePerKelvin); /// /// Get Entropy in KilocaloriesPerKelvin. /// - public double KilocaloriesPerKelvin - { - get { return (_joulesPerKelvin/4.184) / 1e3d; } - } - + public double KilocaloriesPerKelvin => As(EntropyUnit.KilocaloriePerKelvin); /// /// Get Entropy in KilojoulesPerDegreeCelsius. /// - public double KilojoulesPerDegreeCelsius - { - get { return (_joulesPerKelvin) / 1e3d; } - } - + public double KilojoulesPerDegreeCelsius => As(EntropyUnit.KilojoulePerDegreeCelsius); /// /// Get Entropy in KilojoulesPerKelvin. /// - public double KilojoulesPerKelvin - { - get { return (_joulesPerKelvin) / 1e3d; } - } - + public double KilojoulesPerKelvin => As(EntropyUnit.KilojoulePerKelvin); /// /// Get Entropy in MegajoulesPerKelvin. /// - public double MegajoulesPerKelvin - { - get { return (_joulesPerKelvin) / 1e6d; } - } + public double MegajoulesPerKelvin => As(EntropyUnit.MegajoulePerKelvin); #endregion #region Static - public static Entropy Zero - { - get { return new Entropy(); } - } + public static Entropy Zero => new Entropy(0, BaseUnit); /// /// Get Entropy from CaloriesPerKelvin. @@ -200,17 +203,13 @@ public static Entropy Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Entropy FromCaloriesPerKelvin(double caloriesperkelvin) - { - double value = (double) caloriesperkelvin; - return new Entropy(value*4.184); - } #else public static Entropy FromCaloriesPerKelvin(QuantityValue caloriesperkelvin) +#endif { double value = (double) caloriesperkelvin; - return new Entropy((value*4.184)); + return new Entropy(value, EntropyUnit.CaloriePerKelvin); } -#endif /// /// Get Entropy from JoulesPerDegreeCelsius. @@ -218,17 +217,13 @@ public static Entropy FromCaloriesPerKelvin(QuantityValue caloriesperkelvin) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Entropy FromJoulesPerDegreeCelsius(double joulesperdegreecelsius) - { - double value = (double) joulesperdegreecelsius; - return new Entropy(value); - } #else public static Entropy FromJoulesPerDegreeCelsius(QuantityValue joulesperdegreecelsius) +#endif { double value = (double) joulesperdegreecelsius; - return new Entropy((value)); + return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); } -#endif /// /// Get Entropy from JoulesPerKelvin. @@ -236,17 +231,13 @@ public static Entropy FromJoulesPerDegreeCelsius(QuantityValue joulesperdegreece #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Entropy FromJoulesPerKelvin(double joulesperkelvin) - { - double value = (double) joulesperkelvin; - return new Entropy(value); - } #else public static Entropy FromJoulesPerKelvin(QuantityValue joulesperkelvin) +#endif { double value = (double) joulesperkelvin; - return new Entropy((value)); + return new Entropy(value, EntropyUnit.JoulePerKelvin); } -#endif /// /// Get Entropy from KilocaloriesPerKelvin. @@ -254,17 +245,13 @@ public static Entropy FromJoulesPerKelvin(QuantityValue joulesperkelvin) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Entropy FromKilocaloriesPerKelvin(double kilocaloriesperkelvin) - { - double value = (double) kilocaloriesperkelvin; - return new Entropy((value*4.184) * 1e3d); - } #else public static Entropy FromKilocaloriesPerKelvin(QuantityValue kilocaloriesperkelvin) +#endif { double value = (double) kilocaloriesperkelvin; - return new Entropy(((value*4.184) * 1e3d)); + return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); } -#endif /// /// Get Entropy from KilojoulesPerDegreeCelsius. @@ -272,17 +259,13 @@ public static Entropy FromKilocaloriesPerKelvin(QuantityValue kilocaloriesperkel #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Entropy FromKilojoulesPerDegreeCelsius(double kilojoulesperdegreecelsius) - { - double value = (double) kilojoulesperdegreecelsius; - return new Entropy((value) * 1e3d); - } #else public static Entropy FromKilojoulesPerDegreeCelsius(QuantityValue kilojoulesperdegreecelsius) +#endif { double value = (double) kilojoulesperdegreecelsius; - return new Entropy(((value) * 1e3d)); + return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); } -#endif /// /// Get Entropy from KilojoulesPerKelvin. @@ -290,17 +273,13 @@ public static Entropy FromKilojoulesPerDegreeCelsius(QuantityValue kilojoulesper #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Entropy FromKilojoulesPerKelvin(double kilojoulesperkelvin) - { - double value = (double) kilojoulesperkelvin; - return new Entropy((value) * 1e3d); - } #else public static Entropy FromKilojoulesPerKelvin(QuantityValue kilojoulesperkelvin) +#endif { double value = (double) kilojoulesperkelvin; - return new Entropy(((value) * 1e3d)); + return new Entropy(value, EntropyUnit.KilojoulePerKelvin); } -#endif /// /// Get Entropy from MegajoulesPerKelvin. @@ -308,17 +287,13 @@ public static Entropy FromKilojoulesPerKelvin(QuantityValue kilojoulesperkelvin) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Entropy FromMegajoulesPerKelvin(double megajoulesperkelvin) - { - double value = (double) megajoulesperkelvin; - return new Entropy((value) * 1e6d); - } #else public static Entropy FromMegajoulesPerKelvin(QuantityValue megajoulesperkelvin) +#endif { double value = (double) megajoulesperkelvin; - return new Entropy(((value) * 1e6d)); + return new Entropy(value, EntropyUnit.MegajoulePerKelvin); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -443,26 +418,7 @@ public static Entropy From(double value, EntropyUnit fromUnit) public static Entropy From(QuantityValue value, EntropyUnit fromUnit) #endif { - switch (fromUnit) - { - case EntropyUnit.CaloriePerKelvin: - return FromCaloriesPerKelvin(value); - case EntropyUnit.JoulePerDegreeCelsius: - return FromJoulesPerDegreeCelsius(value); - case EntropyUnit.JoulePerKelvin: - return FromJoulesPerKelvin(value); - case EntropyUnit.KilocaloriePerKelvin: - return FromKilocaloriesPerKelvin(value); - case EntropyUnit.KilojoulePerDegreeCelsius: - return FromKilojoulesPerDegreeCelsius(value); - case EntropyUnit.KilojoulePerKelvin: - return FromKilojoulesPerKelvin(value); - case EntropyUnit.MegajoulePerKelvin: - return FromMegajoulesPerKelvin(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Entropy((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -479,26 +435,8 @@ public static Entropy From(QuantityValue value, EntropyUnit fromUnit) { return null; } - switch (fromUnit) - { - case EntropyUnit.CaloriePerKelvin: - return FromCaloriesPerKelvin(value.Value); - case EntropyUnit.JoulePerDegreeCelsius: - return FromJoulesPerDegreeCelsius(value.Value); - case EntropyUnit.JoulePerKelvin: - return FromJoulesPerKelvin(value.Value); - case EntropyUnit.KilocaloriePerKelvin: - return FromKilocaloriesPerKelvin(value.Value); - case EntropyUnit.KilojoulePerDegreeCelsius: - return FromKilojoulesPerDegreeCelsius(value.Value); - case EntropyUnit.KilojoulePerKelvin: - return FromKilojoulesPerKelvin(value.Value); - case EntropyUnit.MegajoulePerKelvin: - return FromMegajoulesPerKelvin(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Entropy((double)value.Value, fromUnit); } #endif @@ -517,12 +455,29 @@ public static string GetAbbreviation(EntropyUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(EntropyUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + EntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -533,37 +488,37 @@ public static string GetAbbreviation(EntropyUnit unit, [CanBeNull] Culture cultu #if !WINDOWS_UWP public static Entropy operator -(Entropy right) { - return new Entropy(-right._joulesPerKelvin); + return new Entropy(-right.Value, right.Unit); } public static Entropy operator +(Entropy left, Entropy right) { - return new Entropy(left._joulesPerKelvin + right._joulesPerKelvin); + return new Entropy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Entropy operator -(Entropy left, Entropy right) { - return new Entropy(left._joulesPerKelvin - right._joulesPerKelvin); + return new Entropy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Entropy operator *(double left, Entropy right) { - return new Entropy(left*right._joulesPerKelvin); + return new Entropy(left * right.Value, right.Unit); } public static Entropy operator *(Entropy left, double right) { - return new Entropy(left._joulesPerKelvin*(double)right); + return new Entropy(left.Value * right, left.Unit); } public static Entropy operator /(Entropy left, double right) { - return new Entropy(left._joulesPerKelvin/(double)right); + return new Entropy(left.Value / right, left.Unit); } public static double operator /(Entropy left, Entropy right) { - return Convert.ToDouble(left._joulesPerKelvin/right._joulesPerKelvin); + return left.JoulesPerKelvin / right.JoulesPerKelvin; } #endif @@ -586,43 +541,43 @@ public int CompareTo(object obj) #endif int CompareTo(Entropy other) { - return _joulesPerKelvin.CompareTo(other._joulesPerKelvin); + return AsBaseUnitJoulesPerKelvin().CompareTo(other.AsBaseUnitJoulesPerKelvin()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Entropy left, Entropy right) { - return left._joulesPerKelvin <= right._joulesPerKelvin; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Entropy left, Entropy right) { - return left._joulesPerKelvin >= right._joulesPerKelvin; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Entropy left, Entropy right) { - return left._joulesPerKelvin < right._joulesPerKelvin; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Entropy left, Entropy right) { - return left._joulesPerKelvin > right._joulesPerKelvin; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Entropy left, Entropy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerKelvin == right._joulesPerKelvin; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Entropy left, Entropy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerKelvin != right._joulesPerKelvin; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -634,7 +589,7 @@ public override bool Equals(object obj) return false; } - return _joulesPerKelvin.Equals(((Entropy) obj)._joulesPerKelvin); + return AsBaseUnitJoulesPerKelvin().Equals(((Entropy) obj).AsBaseUnitJoulesPerKelvin()); } /// @@ -647,12 +602,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Entropy other, Entropy maxError) { - return Math.Abs(_joulesPerKelvin - other._joulesPerKelvin) <= maxError._joulesPerKelvin; + return Math.Abs(AsBaseUnitJoulesPerKelvin() - other.AsBaseUnitJoulesPerKelvin()) <= maxError.AsBaseUnitJoulesPerKelvin(); } public override int GetHashCode() { - return _joulesPerKelvin.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -662,26 +617,25 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(EntropyUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitJoulesPerKelvin(); + switch (unit) { - case EntropyUnit.CaloriePerKelvin: - return CaloriesPerKelvin; - case EntropyUnit.JoulePerDegreeCelsius: - return JoulesPerDegreeCelsius; - case EntropyUnit.JoulePerKelvin: - return JoulesPerKelvin; - case EntropyUnit.KilocaloriePerKelvin: - return KilocaloriesPerKelvin; - case EntropyUnit.KilojoulePerDegreeCelsius: - return KilojoulesPerDegreeCelsius; - case EntropyUnit.KilojoulePerKelvin: - return KilojoulesPerKelvin; - case EntropyUnit.MegajoulePerKelvin: - return MegajoulesPerKelvin; + case EntropyUnit.CaloriePerKelvin: return baseUnitValue/4.184; + case EntropyUnit.JoulePerDegreeCelsius: return baseUnitValue; + case EntropyUnit.JoulePerKelvin: return baseUnitValue; + case EntropyUnit.KilocaloriePerKelvin: return (baseUnitValue/4.184) / 1e3d; + case EntropyUnit.KilojoulePerDegreeCelsius: return (baseUnitValue) / 1e3d; + case EntropyUnit.KilojoulePerKelvin: return (baseUnitValue) / 1e3d; + case EntropyUnit.MegajoulePerKelvin: return (baseUnitValue) / 1e6d; default: throw new NotImplementedException("unit: " + unit); @@ -723,7 +677,11 @@ public static Entropy Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -742,17 +700,24 @@ public static Entropy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Entropy Parse(string str, [CanBeNull] Culture culture) + public static Entropy Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -778,16 +743,41 @@ public static bool TryParse([CanBeNull] string str, out Entropy result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Entropy result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Entropy result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -800,6 +790,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -813,11 +804,14 @@ public static EntropyUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static EntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -826,6 +820,8 @@ public static EntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -838,18 +834,18 @@ public static EntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static EntropyUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static EntropyUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == EntropyUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized EntropyUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -858,6 +854,7 @@ static EntropyUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is JoulePerKelvin /// @@ -869,7 +866,7 @@ static EntropyUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -886,74 +883,135 @@ public string ToString(EntropyUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(EntropyUnit unit, [CanBeNull] Culture culture) + public string ToString( + EntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(EntropyUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + EntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(EntropyUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + EntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Entropy /// - public static Entropy MaxValue - { - get - { - return new Entropy(double.MaxValue); - } - } + public static Entropy MaxValue => new Entropy(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Entropy /// - public static Entropy MinValue + public static Entropy MinValue => new Entropy(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitJoulesPerKelvin() { - get + if (Unit == EntropyUnit.JoulePerKelvin) { return _value; } + + switch (Unit) { - return new Entropy(double.MinValue); - } - } - } + case EntropyUnit.CaloriePerKelvin: return _value*4.184; + case EntropyUnit.JoulePerDegreeCelsius: return _value; + case EntropyUnit.JoulePerKelvin: return _value; + case EntropyUnit.KilocaloriePerKelvin: return (_value*4.184) * 1e3d; + case EntropyUnit.KilojoulePerDegreeCelsius: return (_value) * 1e3d; + case EntropyUnit.KilojoulePerKelvin: return (_value) * 1e3d; + case EntropyUnit.MegajoulePerKelvin: return (_value) * 1e6d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(EntropyUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Flow.g.cs b/UnitsNet/GeneratedCode/Quantities/Flow.g.cs index 6d4dd6a556..b0dbb5b1db 100644 --- a/UnitsNet/GeneratedCode/Quantities/Flow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Flow.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Flow : IComparable, IComparable #endif { /// - /// Base unit of Flow. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly FlowUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _cubicMetersPerSecond; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public FlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Flow() : this(0) + public Flow() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Flow(double cubicmeterspersecond) { - _cubicMetersPerSecond = Convert.ToDouble(cubicmeterspersecond); + _value = Convert.ToDouble(cubicmeterspersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Flow(double numericValue, FlowUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit CubicMeterPerSecond. + /// + /// Value assuming base unit CubicMeterPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Flow(long cubicmeterspersecond) - { - _cubicMetersPerSecond = Convert.ToDouble(cubicmeterspersecond); - } + Flow(long cubicmeterspersecond) : this(Convert.ToDouble(cubicmeterspersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit CubicMeterPerSecond. + /// + /// Value assuming base unit CubicMeterPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Flow(decimal cubicmeterspersecond) - { - _cubicMetersPerSecond = Convert.ToDouble(cubicmeterspersecond); - } + Flow(decimal cubicmeterspersecond) : this(Convert.ToDouble(cubicmeterspersecond), BaseUnit) { } #region Properties @@ -119,234 +156,132 @@ public Flow(double cubicmeterspersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static FlowUnit BaseUnit - { - get { return FlowUnit.CubicMeterPerSecond; } - } + public static FlowUnit BaseUnit => FlowUnit.CubicMeterPerSecond; /// /// All units of measurement for the Flow quantity. /// public static FlowUnit[] Units { get; } = Enum.GetValues(typeof(FlowUnit)).Cast().ToArray(); - /// /// Get Flow in CentilitersPerMinute. /// - public double CentilitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e-2d; } - } - + public double CentilitersPerMinute => As(FlowUnit.CentilitersPerMinute); /// /// Get Flow in CubicDecimetersPerMinute. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicDecimetersPerMinute - { - get { return _cubicMetersPerSecond*60000.00000; } - } - + public double CubicDecimetersPerMinute => As(FlowUnit.CubicDecimeterPerMinute); /// /// Get Flow in CubicFeetPerHour. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicFeetPerHour - { - get { return _cubicMetersPerSecond/7.8657907199999087346816086183876e-6; } - } - + public double CubicFeetPerHour => As(FlowUnit.CubicFootPerHour); /// /// Get Flow in CubicFeetPerMinute. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicFeetPerMinute - { - get { return _cubicMetersPerSecond*2118.88000326; } - } - + public double CubicFeetPerMinute => As(FlowUnit.CubicFootPerMinute); /// /// Get Flow in CubicFeetPerSecond. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicFeetPerSecond - { - get { return _cubicMetersPerSecond*35.314666721; } - } - + public double CubicFeetPerSecond => As(FlowUnit.CubicFootPerSecond); /// /// Get Flow in CubicMetersPerHour. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicMetersPerHour - { - get { return _cubicMetersPerSecond*3600; } - } - + public double CubicMetersPerHour => As(FlowUnit.CubicMeterPerHour); /// /// Get Flow in CubicMetersPerMinute. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicMetersPerMinute - { - get { return _cubicMetersPerSecond*60; } - } - + public double CubicMetersPerMinute => As(FlowUnit.CubicMeterPerMinute); /// /// Get Flow in CubicMetersPerSecond. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicMetersPerSecond - { - get { return _cubicMetersPerSecond; } - } - + public double CubicMetersPerSecond => As(FlowUnit.CubicMeterPerSecond); /// /// Get Flow in CubicYardsPerHour. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicYardsPerHour - { - get { return _cubicMetersPerSecond/2.1237634944E-4; } - } - + public double CubicYardsPerHour => As(FlowUnit.CubicYardPerHour); /// /// Get Flow in CubicYardsPerMinute. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicYardsPerMinute - { - get { return _cubicMetersPerSecond/0.0127425809664; } - } - + public double CubicYardsPerMinute => As(FlowUnit.CubicYardPerMinute); /// /// Get Flow in CubicYardsPerSecond. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double CubicYardsPerSecond - { - get { return _cubicMetersPerSecond/0.764554857984; } - } - + public double CubicYardsPerSecond => As(FlowUnit.CubicYardPerSecond); /// /// Get Flow in DecilitersPerMinute. /// - public double DecilitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e-1d; } - } - + public double DecilitersPerMinute => As(FlowUnit.DecilitersPerMinute); /// /// Get Flow in KilolitersPerMinute. /// - public double KilolitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e3d; } - } - + public double KilolitersPerMinute => As(FlowUnit.KilolitersPerMinute); /// /// Get Flow in LitersPerHour. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double LitersPerHour - { - get { return _cubicMetersPerSecond*3600000.000; } - } - + public double LitersPerHour => As(FlowUnit.LitersPerHour); /// /// Get Flow in LitersPerMinute. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double LitersPerMinute - { - get { return _cubicMetersPerSecond*60000.00000; } - } - + public double LitersPerMinute => As(FlowUnit.LitersPerMinute); /// /// Get Flow in LitersPerSecond. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double LitersPerSecond - { - get { return _cubicMetersPerSecond*1000; } - } - + public double LitersPerSecond => As(FlowUnit.LitersPerSecond); /// /// Get Flow in MicrolitersPerMinute. /// - public double MicrolitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e-6d; } - } - + public double MicrolitersPerMinute => As(FlowUnit.MicrolitersPerMinute); /// /// Get Flow in MillilitersPerMinute. /// - public double MillilitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e-3d; } - } - + public double MillilitersPerMinute => As(FlowUnit.MillilitersPerMinute); /// /// Get Flow in MillionUsGallonsPerDay. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double MillionUsGallonsPerDay - { - get { return _cubicMetersPerSecond*22.824465227; } - } - + public double MillionUsGallonsPerDay => As(FlowUnit.MillionUsGallonsPerDay); /// /// Get Flow in NanolitersPerMinute. /// - public double NanolitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e-9d; } - } - + public double NanolitersPerMinute => As(FlowUnit.NanolitersPerMinute); /// /// Get Flow in OilBarrelsPerDay. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double OilBarrelsPerDay - { - get { return _cubicMetersPerSecond/1.8401307283333333333333333333333e-6; } - } - + public double OilBarrelsPerDay => As(FlowUnit.OilBarrelsPerDay); /// /// Get Flow in UsGallonsPerHour. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double UsGallonsPerHour - { - get { return _cubicMetersPerSecond*951019.38848933424; } - } - + public double UsGallonsPerHour => As(FlowUnit.UsGallonsPerHour); /// /// Get Flow in UsGallonsPerMinute. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double UsGallonsPerMinute - { - get { return _cubicMetersPerSecond*15850.323141489; } - } - + public double UsGallonsPerMinute => As(FlowUnit.UsGallonsPerMinute); /// /// Get Flow in UsGallonsPerSecond. /// [System.Obsolete("Deprecated due to github issue #363, please use VolumeFlow instead")] - public double UsGallonsPerSecond - { - get { return _cubicMetersPerSecond*264.1720523581484; } - } + public double UsGallonsPerSecond => As(FlowUnit.UsGallonsPerSecond); #endregion #region Static - public static Flow Zero - { - get { return new Flow(); } - } + public static Flow Zero => new Flow(0, BaseUnit); /// /// Get Flow from CentilitersPerMinute. @@ -354,17 +289,13 @@ public static Flow Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCentilitersPerMinute(double centilitersperminute) - { - double value = (double) centilitersperminute; - return new Flow((value/60000.00000) * 1e-2d); - } #else public static Flow FromCentilitersPerMinute(QuantityValue centilitersperminute) +#endif { double value = (double) centilitersperminute; - return new Flow(((value/60000.00000) * 1e-2d)); + return new Flow(value, FlowUnit.CentilitersPerMinute); } -#endif /// /// Get Flow from CubicDecimetersPerMinute. @@ -372,17 +303,13 @@ public static Flow FromCentilitersPerMinute(QuantityValue centilitersperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCubicDecimetersPerMinute(double cubicdecimetersperminute) - { - double value = (double) cubicdecimetersperminute; - return new Flow(value/60000.00000); - } #else public static Flow FromCubicDecimetersPerMinute(QuantityValue cubicdecimetersperminute) +#endif { double value = (double) cubicdecimetersperminute; - return new Flow((value/60000.00000)); + return new Flow(value, FlowUnit.CubicDecimeterPerMinute); } -#endif /// /// Get Flow from CubicFeetPerHour. @@ -390,17 +317,13 @@ public static Flow FromCubicDecimetersPerMinute(QuantityValue cubicdecimetersper #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCubicFeetPerHour(double cubicfeetperhour) - { - double value = (double) cubicfeetperhour; - return new Flow(value*7.8657907199999087346816086183876e-6); - } #else public static Flow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) +#endif { double value = (double) cubicfeetperhour; - return new Flow((value*7.8657907199999087346816086183876e-6)); + return new Flow(value, FlowUnit.CubicFootPerHour); } -#endif /// /// Get Flow from CubicFeetPerMinute. @@ -408,17 +331,13 @@ public static Flow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCubicFeetPerMinute(double cubicfeetperminute) - { - double value = (double) cubicfeetperminute; - return new Flow(value/2118.88000326); - } #else public static Flow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute) +#endif { double value = (double) cubicfeetperminute; - return new Flow((value/2118.88000326)); + return new Flow(value, FlowUnit.CubicFootPerMinute); } -#endif /// /// Get Flow from CubicFeetPerSecond. @@ -426,17 +345,13 @@ public static Flow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCubicFeetPerSecond(double cubicfeetpersecond) - { - double value = (double) cubicfeetpersecond; - return new Flow(value/35.314666721); - } #else public static Flow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond) +#endif { double value = (double) cubicfeetpersecond; - return new Flow((value/35.314666721)); + return new Flow(value, FlowUnit.CubicFootPerSecond); } -#endif /// /// Get Flow from CubicMetersPerHour. @@ -444,17 +359,13 @@ public static Flow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCubicMetersPerHour(double cubicmetersperhour) - { - double value = (double) cubicmetersperhour; - return new Flow(value/3600); - } #else public static Flow FromCubicMetersPerHour(QuantityValue cubicmetersperhour) +#endif { double value = (double) cubicmetersperhour; - return new Flow((value/3600)); + return new Flow(value, FlowUnit.CubicMeterPerHour); } -#endif /// /// Get Flow from CubicMetersPerMinute. @@ -462,17 +373,13 @@ public static Flow FromCubicMetersPerHour(QuantityValue cubicmetersperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCubicMetersPerMinute(double cubicmetersperminute) - { - double value = (double) cubicmetersperminute; - return new Flow(value/60); - } #else public static Flow FromCubicMetersPerMinute(QuantityValue cubicmetersperminute) +#endif { double value = (double) cubicmetersperminute; - return new Flow((value/60)); + return new Flow(value, FlowUnit.CubicMeterPerMinute); } -#endif /// /// Get Flow from CubicMetersPerSecond. @@ -480,17 +387,13 @@ public static Flow FromCubicMetersPerMinute(QuantityValue cubicmetersperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCubicMetersPerSecond(double cubicmeterspersecond) - { - double value = (double) cubicmeterspersecond; - return new Flow(value); - } #else public static Flow FromCubicMetersPerSecond(QuantityValue cubicmeterspersecond) +#endif { double value = (double) cubicmeterspersecond; - return new Flow((value)); + return new Flow(value, FlowUnit.CubicMeterPerSecond); } -#endif /// /// Get Flow from CubicYardsPerHour. @@ -498,17 +401,13 @@ public static Flow FromCubicMetersPerSecond(QuantityValue cubicmeterspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCubicYardsPerHour(double cubicyardsperhour) - { - double value = (double) cubicyardsperhour; - return new Flow(value*2.1237634944E-4); - } #else public static Flow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) +#endif { double value = (double) cubicyardsperhour; - return new Flow((value*2.1237634944E-4)); + return new Flow(value, FlowUnit.CubicYardPerHour); } -#endif /// /// Get Flow from CubicYardsPerMinute. @@ -516,17 +415,13 @@ public static Flow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCubicYardsPerMinute(double cubicyardsperminute) - { - double value = (double) cubicyardsperminute; - return new Flow(value*0.0127425809664); - } #else public static Flow FromCubicYardsPerMinute(QuantityValue cubicyardsperminute) +#endif { double value = (double) cubicyardsperminute; - return new Flow((value*0.0127425809664)); + return new Flow(value, FlowUnit.CubicYardPerMinute); } -#endif /// /// Get Flow from CubicYardsPerSecond. @@ -534,17 +429,13 @@ public static Flow FromCubicYardsPerMinute(QuantityValue cubicyardsperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromCubicYardsPerSecond(double cubicyardspersecond) - { - double value = (double) cubicyardspersecond; - return new Flow(value*0.764554857984); - } #else public static Flow FromCubicYardsPerSecond(QuantityValue cubicyardspersecond) +#endif { double value = (double) cubicyardspersecond; - return new Flow((value*0.764554857984)); + return new Flow(value, FlowUnit.CubicYardPerSecond); } -#endif /// /// Get Flow from DecilitersPerMinute. @@ -552,17 +443,13 @@ public static Flow FromCubicYardsPerSecond(QuantityValue cubicyardspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromDecilitersPerMinute(double decilitersperminute) - { - double value = (double) decilitersperminute; - return new Flow((value/60000.00000) * 1e-1d); - } #else public static Flow FromDecilitersPerMinute(QuantityValue decilitersperminute) +#endif { double value = (double) decilitersperminute; - return new Flow(((value/60000.00000) * 1e-1d)); + return new Flow(value, FlowUnit.DecilitersPerMinute); } -#endif /// /// Get Flow from KilolitersPerMinute. @@ -570,17 +457,13 @@ public static Flow FromDecilitersPerMinute(QuantityValue decilitersperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromKilolitersPerMinute(double kilolitersperminute) - { - double value = (double) kilolitersperminute; - return new Flow((value/60000.00000) * 1e3d); - } #else public static Flow FromKilolitersPerMinute(QuantityValue kilolitersperminute) +#endif { double value = (double) kilolitersperminute; - return new Flow(((value/60000.00000) * 1e3d)); + return new Flow(value, FlowUnit.KilolitersPerMinute); } -#endif /// /// Get Flow from LitersPerHour. @@ -588,17 +471,13 @@ public static Flow FromKilolitersPerMinute(QuantityValue kilolitersperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromLitersPerHour(double litersperhour) - { - double value = (double) litersperhour; - return new Flow(value/3600000.000); - } #else public static Flow FromLitersPerHour(QuantityValue litersperhour) +#endif { double value = (double) litersperhour; - return new Flow((value/3600000.000)); + return new Flow(value, FlowUnit.LitersPerHour); } -#endif /// /// Get Flow from LitersPerMinute. @@ -606,17 +485,13 @@ public static Flow FromLitersPerHour(QuantityValue litersperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromLitersPerMinute(double litersperminute) - { - double value = (double) litersperminute; - return new Flow(value/60000.00000); - } #else public static Flow FromLitersPerMinute(QuantityValue litersperminute) +#endif { double value = (double) litersperminute; - return new Flow((value/60000.00000)); + return new Flow(value, FlowUnit.LitersPerMinute); } -#endif /// /// Get Flow from LitersPerSecond. @@ -624,17 +499,13 @@ public static Flow FromLitersPerMinute(QuantityValue litersperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromLitersPerSecond(double literspersecond) - { - double value = (double) literspersecond; - return new Flow(value/1000); - } #else public static Flow FromLitersPerSecond(QuantityValue literspersecond) +#endif { double value = (double) literspersecond; - return new Flow((value/1000)); + return new Flow(value, FlowUnit.LitersPerSecond); } -#endif /// /// Get Flow from MicrolitersPerMinute. @@ -642,17 +513,13 @@ public static Flow FromLitersPerSecond(QuantityValue literspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromMicrolitersPerMinute(double microlitersperminute) - { - double value = (double) microlitersperminute; - return new Flow((value/60000.00000) * 1e-6d); - } #else public static Flow FromMicrolitersPerMinute(QuantityValue microlitersperminute) +#endif { double value = (double) microlitersperminute; - return new Flow(((value/60000.00000) * 1e-6d)); + return new Flow(value, FlowUnit.MicrolitersPerMinute); } -#endif /// /// Get Flow from MillilitersPerMinute. @@ -660,17 +527,13 @@ public static Flow FromMicrolitersPerMinute(QuantityValue microlitersperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromMillilitersPerMinute(double millilitersperminute) - { - double value = (double) millilitersperminute; - return new Flow((value/60000.00000) * 1e-3d); - } #else public static Flow FromMillilitersPerMinute(QuantityValue millilitersperminute) +#endif { double value = (double) millilitersperminute; - return new Flow(((value/60000.00000) * 1e-3d)); + return new Flow(value, FlowUnit.MillilitersPerMinute); } -#endif /// /// Get Flow from MillionUsGallonsPerDay. @@ -678,17 +541,13 @@ public static Flow FromMillilitersPerMinute(QuantityValue millilitersperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromMillionUsGallonsPerDay(double millionusgallonsperday) - { - double value = (double) millionusgallonsperday; - return new Flow(value/22.824465227); - } #else public static Flow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperday) +#endif { double value = (double) millionusgallonsperday; - return new Flow((value/22.824465227)); + return new Flow(value, FlowUnit.MillionUsGallonsPerDay); } -#endif /// /// Get Flow from NanolitersPerMinute. @@ -696,17 +555,13 @@ public static Flow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperd #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromNanolitersPerMinute(double nanolitersperminute) - { - double value = (double) nanolitersperminute; - return new Flow((value/60000.00000) * 1e-9d); - } #else public static Flow FromNanolitersPerMinute(QuantityValue nanolitersperminute) +#endif { double value = (double) nanolitersperminute; - return new Flow(((value/60000.00000) * 1e-9d)); + return new Flow(value, FlowUnit.NanolitersPerMinute); } -#endif /// /// Get Flow from OilBarrelsPerDay. @@ -714,17 +569,13 @@ public static Flow FromNanolitersPerMinute(QuantityValue nanolitersperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromOilBarrelsPerDay(double oilbarrelsperday) - { - double value = (double) oilbarrelsperday; - return new Flow(value*1.8401307283333333333333333333333e-6); - } #else public static Flow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) +#endif { double value = (double) oilbarrelsperday; - return new Flow((value*1.8401307283333333333333333333333e-6)); + return new Flow(value, FlowUnit.OilBarrelsPerDay); } -#endif /// /// Get Flow from UsGallonsPerHour. @@ -732,17 +583,13 @@ public static Flow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromUsGallonsPerHour(double usgallonsperhour) - { - double value = (double) usgallonsperhour; - return new Flow(value/951019.38848933424); - } #else public static Flow FromUsGallonsPerHour(QuantityValue usgallonsperhour) +#endif { double value = (double) usgallonsperhour; - return new Flow((value/951019.38848933424)); + return new Flow(value, FlowUnit.UsGallonsPerHour); } -#endif /// /// Get Flow from UsGallonsPerMinute. @@ -750,17 +597,13 @@ public static Flow FromUsGallonsPerHour(QuantityValue usgallonsperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromUsGallonsPerMinute(double usgallonsperminute) - { - double value = (double) usgallonsperminute; - return new Flow(value/15850.323141489); - } #else public static Flow FromUsGallonsPerMinute(QuantityValue usgallonsperminute) +#endif { double value = (double) usgallonsperminute; - return new Flow((value/15850.323141489)); + return new Flow(value, FlowUnit.UsGallonsPerMinute); } -#endif /// /// Get Flow from UsGallonsPerSecond. @@ -768,17 +611,13 @@ public static Flow FromUsGallonsPerMinute(QuantityValue usgallonsperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Flow FromUsGallonsPerSecond(double usgallonspersecond) - { - double value = (double) usgallonspersecond; - return new Flow(value/264.1720523581484); - } #else public static Flow FromUsGallonsPerSecond(QuantityValue usgallonspersecond) +#endif { double value = (double) usgallonspersecond; - return new Flow((value/264.1720523581484)); + return new Flow(value, FlowUnit.UsGallonsPerSecond); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1158,60 +997,7 @@ public static Flow From(double value, FlowUnit fromUnit) public static Flow From(QuantityValue value, FlowUnit fromUnit) #endif { - switch (fromUnit) - { - case FlowUnit.CentilitersPerMinute: - return FromCentilitersPerMinute(value); - case FlowUnit.CubicDecimeterPerMinute: - return FromCubicDecimetersPerMinute(value); - case FlowUnit.CubicFootPerHour: - return FromCubicFeetPerHour(value); - case FlowUnit.CubicFootPerMinute: - return FromCubicFeetPerMinute(value); - case FlowUnit.CubicFootPerSecond: - return FromCubicFeetPerSecond(value); - case FlowUnit.CubicMeterPerHour: - return FromCubicMetersPerHour(value); - case FlowUnit.CubicMeterPerMinute: - return FromCubicMetersPerMinute(value); - case FlowUnit.CubicMeterPerSecond: - return FromCubicMetersPerSecond(value); - case FlowUnit.CubicYardPerHour: - return FromCubicYardsPerHour(value); - case FlowUnit.CubicYardPerMinute: - return FromCubicYardsPerMinute(value); - case FlowUnit.CubicYardPerSecond: - return FromCubicYardsPerSecond(value); - case FlowUnit.DecilitersPerMinute: - return FromDecilitersPerMinute(value); - case FlowUnit.KilolitersPerMinute: - return FromKilolitersPerMinute(value); - case FlowUnit.LitersPerHour: - return FromLitersPerHour(value); - case FlowUnit.LitersPerMinute: - return FromLitersPerMinute(value); - case FlowUnit.LitersPerSecond: - return FromLitersPerSecond(value); - case FlowUnit.MicrolitersPerMinute: - return FromMicrolitersPerMinute(value); - case FlowUnit.MillilitersPerMinute: - return FromMillilitersPerMinute(value); - case FlowUnit.MillionUsGallonsPerDay: - return FromMillionUsGallonsPerDay(value); - case FlowUnit.NanolitersPerMinute: - return FromNanolitersPerMinute(value); - case FlowUnit.OilBarrelsPerDay: - return FromOilBarrelsPerDay(value); - case FlowUnit.UsGallonsPerHour: - return FromUsGallonsPerHour(value); - case FlowUnit.UsGallonsPerMinute: - return FromUsGallonsPerMinute(value); - case FlowUnit.UsGallonsPerSecond: - return FromUsGallonsPerSecond(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Flow((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1228,60 +1014,8 @@ public static Flow From(QuantityValue value, FlowUnit fromUnit) { return null; } - switch (fromUnit) - { - case FlowUnit.CentilitersPerMinute: - return FromCentilitersPerMinute(value.Value); - case FlowUnit.CubicDecimeterPerMinute: - return FromCubicDecimetersPerMinute(value.Value); - case FlowUnit.CubicFootPerHour: - return FromCubicFeetPerHour(value.Value); - case FlowUnit.CubicFootPerMinute: - return FromCubicFeetPerMinute(value.Value); - case FlowUnit.CubicFootPerSecond: - return FromCubicFeetPerSecond(value.Value); - case FlowUnit.CubicMeterPerHour: - return FromCubicMetersPerHour(value.Value); - case FlowUnit.CubicMeterPerMinute: - return FromCubicMetersPerMinute(value.Value); - case FlowUnit.CubicMeterPerSecond: - return FromCubicMetersPerSecond(value.Value); - case FlowUnit.CubicYardPerHour: - return FromCubicYardsPerHour(value.Value); - case FlowUnit.CubicYardPerMinute: - return FromCubicYardsPerMinute(value.Value); - case FlowUnit.CubicYardPerSecond: - return FromCubicYardsPerSecond(value.Value); - case FlowUnit.DecilitersPerMinute: - return FromDecilitersPerMinute(value.Value); - case FlowUnit.KilolitersPerMinute: - return FromKilolitersPerMinute(value.Value); - case FlowUnit.LitersPerHour: - return FromLitersPerHour(value.Value); - case FlowUnit.LitersPerMinute: - return FromLitersPerMinute(value.Value); - case FlowUnit.LitersPerSecond: - return FromLitersPerSecond(value.Value); - case FlowUnit.MicrolitersPerMinute: - return FromMicrolitersPerMinute(value.Value); - case FlowUnit.MillilitersPerMinute: - return FromMillilitersPerMinute(value.Value); - case FlowUnit.MillionUsGallonsPerDay: - return FromMillionUsGallonsPerDay(value.Value); - case FlowUnit.NanolitersPerMinute: - return FromNanolitersPerMinute(value.Value); - case FlowUnit.OilBarrelsPerDay: - return FromOilBarrelsPerDay(value.Value); - case FlowUnit.UsGallonsPerHour: - return FromUsGallonsPerHour(value.Value); - case FlowUnit.UsGallonsPerMinute: - return FromUsGallonsPerMinute(value.Value); - case FlowUnit.UsGallonsPerSecond: - return FromUsGallonsPerSecond(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Flow((double)value.Value, fromUnit); } #endif @@ -1300,12 +1034,29 @@ public static string GetAbbreviation(FlowUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(FlowUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + FlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1316,37 +1067,37 @@ public static string GetAbbreviation(FlowUnit unit, [CanBeNull] Culture culture) #if !WINDOWS_UWP public static Flow operator -(Flow right) { - return new Flow(-right._cubicMetersPerSecond); + return new Flow(-right.Value, right.Unit); } public static Flow operator +(Flow left, Flow right) { - return new Flow(left._cubicMetersPerSecond + right._cubicMetersPerSecond); + return new Flow(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Flow operator -(Flow left, Flow right) { - return new Flow(left._cubicMetersPerSecond - right._cubicMetersPerSecond); + return new Flow(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Flow operator *(double left, Flow right) { - return new Flow(left*right._cubicMetersPerSecond); + return new Flow(left * right.Value, right.Unit); } public static Flow operator *(Flow left, double right) { - return new Flow(left._cubicMetersPerSecond*(double)right); + return new Flow(left.Value * right, left.Unit); } public static Flow operator /(Flow left, double right) { - return new Flow(left._cubicMetersPerSecond/(double)right); + return new Flow(left.Value / right, left.Unit); } public static double operator /(Flow left, Flow right) { - return Convert.ToDouble(left._cubicMetersPerSecond/right._cubicMetersPerSecond); + return left.CubicMetersPerSecond / right.CubicMetersPerSecond; } #endif @@ -1369,43 +1120,43 @@ public int CompareTo(object obj) #endif int CompareTo(Flow other) { - return _cubicMetersPerSecond.CompareTo(other._cubicMetersPerSecond); + return AsBaseUnitCubicMetersPerSecond().CompareTo(other.AsBaseUnitCubicMetersPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Flow left, Flow right) { - return left._cubicMetersPerSecond <= right._cubicMetersPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Flow left, Flow right) { - return left._cubicMetersPerSecond >= right._cubicMetersPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Flow left, Flow right) { - return left._cubicMetersPerSecond < right._cubicMetersPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Flow left, Flow right) { - return left._cubicMetersPerSecond > right._cubicMetersPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Flow left, Flow right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._cubicMetersPerSecond == right._cubicMetersPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Flow left, Flow right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._cubicMetersPerSecond != right._cubicMetersPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1417,7 +1168,7 @@ public override bool Equals(object obj) return false; } - return _cubicMetersPerSecond.Equals(((Flow) obj)._cubicMetersPerSecond); + return AsBaseUnitCubicMetersPerSecond().Equals(((Flow) obj).AsBaseUnitCubicMetersPerSecond()); } /// @@ -1430,12 +1181,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Flow other, Flow maxError) { - return Math.Abs(_cubicMetersPerSecond - other._cubicMetersPerSecond) <= maxError._cubicMetersPerSecond; + return Math.Abs(AsBaseUnitCubicMetersPerSecond() - other.AsBaseUnitCubicMetersPerSecond()) <= maxError.AsBaseUnitCubicMetersPerSecond(); } public override int GetHashCode() { - return _cubicMetersPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1445,60 +1196,42 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(FlowUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitCubicMetersPerSecond(); + switch (unit) { - case FlowUnit.CentilitersPerMinute: - return CentilitersPerMinute; - case FlowUnit.CubicDecimeterPerMinute: - return CubicDecimetersPerMinute; - case FlowUnit.CubicFootPerHour: - return CubicFeetPerHour; - case FlowUnit.CubicFootPerMinute: - return CubicFeetPerMinute; - case FlowUnit.CubicFootPerSecond: - return CubicFeetPerSecond; - case FlowUnit.CubicMeterPerHour: - return CubicMetersPerHour; - case FlowUnit.CubicMeterPerMinute: - return CubicMetersPerMinute; - case FlowUnit.CubicMeterPerSecond: - return CubicMetersPerSecond; - case FlowUnit.CubicYardPerHour: - return CubicYardsPerHour; - case FlowUnit.CubicYardPerMinute: - return CubicYardsPerMinute; - case FlowUnit.CubicYardPerSecond: - return CubicYardsPerSecond; - case FlowUnit.DecilitersPerMinute: - return DecilitersPerMinute; - case FlowUnit.KilolitersPerMinute: - return KilolitersPerMinute; - case FlowUnit.LitersPerHour: - return LitersPerHour; - case FlowUnit.LitersPerMinute: - return LitersPerMinute; - case FlowUnit.LitersPerSecond: - return LitersPerSecond; - case FlowUnit.MicrolitersPerMinute: - return MicrolitersPerMinute; - case FlowUnit.MillilitersPerMinute: - return MillilitersPerMinute; - case FlowUnit.MillionUsGallonsPerDay: - return MillionUsGallonsPerDay; - case FlowUnit.NanolitersPerMinute: - return NanolitersPerMinute; - case FlowUnit.OilBarrelsPerDay: - return OilBarrelsPerDay; - case FlowUnit.UsGallonsPerHour: - return UsGallonsPerHour; - case FlowUnit.UsGallonsPerMinute: - return UsGallonsPerMinute; - case FlowUnit.UsGallonsPerSecond: - return UsGallonsPerSecond; + case FlowUnit.CentilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-2d; + case FlowUnit.CubicDecimeterPerMinute: return baseUnitValue*60000.00000; + case FlowUnit.CubicFootPerHour: return baseUnitValue/7.8657907199999087346816086183876e-6; + case FlowUnit.CubicFootPerMinute: return baseUnitValue*2118.88000326; + case FlowUnit.CubicFootPerSecond: return baseUnitValue*35.314666721; + case FlowUnit.CubicMeterPerHour: return baseUnitValue*3600; + case FlowUnit.CubicMeterPerMinute: return baseUnitValue*60; + case FlowUnit.CubicMeterPerSecond: return baseUnitValue; + case FlowUnit.CubicYardPerHour: return baseUnitValue/2.1237634944E-4; + case FlowUnit.CubicYardPerMinute: return baseUnitValue/0.0127425809664; + case FlowUnit.CubicYardPerSecond: return baseUnitValue/0.764554857984; + case FlowUnit.DecilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-1d; + case FlowUnit.KilolitersPerMinute: return (baseUnitValue*60000.00000) / 1e3d; + case FlowUnit.LitersPerHour: return baseUnitValue*3600000.000; + case FlowUnit.LitersPerMinute: return baseUnitValue*60000.00000; + case FlowUnit.LitersPerSecond: return baseUnitValue*1000; + case FlowUnit.MicrolitersPerMinute: return (baseUnitValue*60000.00000) / 1e-6d; + case FlowUnit.MillilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-3d; + case FlowUnit.MillionUsGallonsPerDay: return baseUnitValue*22.824465227; + case FlowUnit.NanolitersPerMinute: return (baseUnitValue*60000.00000) / 1e-9d; + case FlowUnit.OilBarrelsPerDay: return baseUnitValue/1.8401307283333333333333333333333e-6; + case FlowUnit.UsGallonsPerHour: return baseUnitValue*951019.38848933424; + case FlowUnit.UsGallonsPerMinute: return baseUnitValue*15850.323141489; + case FlowUnit.UsGallonsPerSecond: return baseUnitValue*264.1720523581484; default: throw new NotImplementedException("unit: " + unit); @@ -1540,7 +1273,11 @@ public static Flow Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1559,17 +1296,24 @@ public static Flow Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Flow Parse(string str, [CanBeNull] Culture culture) + public static Flow Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1595,16 +1339,41 @@ public static bool TryParse([CanBeNull] string str, out Flow result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Flow result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Flow result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1617,6 +1386,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1630,11 +1400,14 @@ public static FlowUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static FlowUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1643,6 +1416,8 @@ public static FlowUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1655,18 +1430,18 @@ public static FlowUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static FlowUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static FlowUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == FlowUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized FlowUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1675,6 +1450,7 @@ static FlowUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is CubicMeterPerSecond /// @@ -1686,7 +1462,7 @@ static FlowUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1703,74 +1479,152 @@ public string ToString(FlowUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(FlowUnit unit, [CanBeNull] Culture culture) + public string ToString( + FlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(FlowUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + FlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(FlowUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + FlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Flow /// - public static Flow MaxValue - { - get - { - return new Flow(double.MaxValue); - } - } + public static Flow MaxValue => new Flow(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Flow /// - public static Flow MinValue + public static Flow MinValue => new Flow(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitCubicMetersPerSecond() { - get + if (Unit == FlowUnit.CubicMeterPerSecond) { return _value; } + + switch (Unit) { - return new Flow(double.MinValue); - } - } - } + case FlowUnit.CentilitersPerMinute: return (_value/60000.00000) * 1e-2d; + case FlowUnit.CubicDecimeterPerMinute: return _value/60000.00000; + case FlowUnit.CubicFootPerHour: return _value*7.8657907199999087346816086183876e-6; + case FlowUnit.CubicFootPerMinute: return _value/2118.88000326; + case FlowUnit.CubicFootPerSecond: return _value/35.314666721; + case FlowUnit.CubicMeterPerHour: return _value/3600; + case FlowUnit.CubicMeterPerMinute: return _value/60; + case FlowUnit.CubicMeterPerSecond: return _value; + case FlowUnit.CubicYardPerHour: return _value*2.1237634944E-4; + case FlowUnit.CubicYardPerMinute: return _value*0.0127425809664; + case FlowUnit.CubicYardPerSecond: return _value*0.764554857984; + case FlowUnit.DecilitersPerMinute: return (_value/60000.00000) * 1e-1d; + case FlowUnit.KilolitersPerMinute: return (_value/60000.00000) * 1e3d; + case FlowUnit.LitersPerHour: return _value/3600000.000; + case FlowUnit.LitersPerMinute: return _value/60000.00000; + case FlowUnit.LitersPerSecond: return _value/1000; + case FlowUnit.MicrolitersPerMinute: return (_value/60000.00000) * 1e-6d; + case FlowUnit.MillilitersPerMinute: return (_value/60000.00000) * 1e-3d; + case FlowUnit.MillionUsGallonsPerDay: return _value/22.824465227; + case FlowUnit.NanolitersPerMinute: return (_value/60000.00000) * 1e-9d; + case FlowUnit.OilBarrelsPerDay: return _value*1.8401307283333333333333333333333e-6; + case FlowUnit.UsGallonsPerHour: return _value/951019.38848933424; + case FlowUnit.UsGallonsPerMinute: return _value/15850.323141489; + case FlowUnit.UsGallonsPerSecond: return _value/264.1720523581484; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(FlowUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Force.g.cs b/UnitsNet/GeneratedCode/Quantities/Force.g.cs index 4787f72af6..44fc73a9d4 100644 --- a/UnitsNet/GeneratedCode/Quantities/Force.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Force.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Force : IComparable, IComparable #endif { /// - /// Base unit of Force. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _newtons; + private readonly ForceUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Force() : this(0) + public Force() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Force(double newtons) { - _newtons = Convert.ToDouble(newtons); + _value = Convert.ToDouble(newtons); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Force(double numericValue, ForceUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Newton. + /// + /// Value assuming base unit Newton. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Force(long newtons) - { - _newtons = Convert.ToDouble(newtons); - } + Force(long newtons) : this(Convert.ToDouble(newtons), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Newton. + /// + /// Value assuming base unit Newton. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Force(decimal newtons) - { - _newtons = Convert.ToDouble(newtons); - } + Force(decimal newtons) : this(Convert.ToDouble(newtons), BaseUnit) { } #region Properties @@ -119,104 +156,58 @@ public Force(double newtons) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ForceUnit BaseUnit - { - get { return ForceUnit.Newton; } - } + public static ForceUnit BaseUnit => ForceUnit.Newton; /// /// All units of measurement for the Force quantity. /// public static ForceUnit[] Units { get; } = Enum.GetValues(typeof(ForceUnit)).Cast().ToArray(); - /// /// Get Force in Decanewtons. /// - public double Decanewtons - { - get { return (_newtons) / 1e1d; } - } - + public double Decanewtons => As(ForceUnit.Decanewton); /// /// Get Force in Dyne. /// - public double Dyne - { - get { return _newtons*1e5; } - } - + public double Dyne => As(ForceUnit.Dyn); /// /// Get Force in KilogramsForce. /// - public double KilogramsForce - { - get { return _newtons/9.80665002864; } - } - + public double KilogramsForce => As(ForceUnit.KilogramForce); /// /// Get Force in Kilonewtons. /// - public double Kilonewtons - { - get { return (_newtons) / 1e3d; } - } - + public double Kilonewtons => As(ForceUnit.Kilonewton); /// /// Get Force in KiloPonds. /// - public double KiloPonds - { - get { return _newtons/9.80665002864; } - } - + public double KiloPonds => As(ForceUnit.KiloPond); /// /// Get Force in Meganewtons. /// - public double Meganewtons - { - get { return (_newtons) / 1e6d; } - } - + public double Meganewtons => As(ForceUnit.Meganewton); /// /// Get Force in Newtons. /// - public double Newtons - { - get { return _newtons; } - } - + public double Newtons => As(ForceUnit.Newton); /// /// Get Force in Poundals. /// - public double Poundals - { - get { return _newtons/0.13825502798973041652092282466083; } - } - + public double Poundals => As(ForceUnit.Poundal); /// /// Get Force in PoundsForce. /// - public double PoundsForce - { - get { return _newtons/4.4482216152605095551842641431421; } - } - + public double PoundsForce => As(ForceUnit.PoundForce); /// /// Get Force in TonnesForce. /// - public double TonnesForce - { - get { return _newtons/9.80665002864/1000; } - } + public double TonnesForce => As(ForceUnit.TonneForce); #endregion #region Static - public static Force Zero - { - get { return new Force(); } - } + public static Force Zero => new Force(0, BaseUnit); /// /// Get Force from Decanewtons. @@ -224,17 +215,13 @@ public static Force Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Force FromDecanewtons(double decanewtons) - { - double value = (double) decanewtons; - return new Force((value) * 1e1d); - } #else public static Force FromDecanewtons(QuantityValue decanewtons) +#endif { double value = (double) decanewtons; - return new Force(((value) * 1e1d)); + return new Force(value, ForceUnit.Decanewton); } -#endif /// /// Get Force from Dyne. @@ -242,17 +229,13 @@ public static Force FromDecanewtons(QuantityValue decanewtons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Force FromDyne(double dyne) - { - double value = (double) dyne; - return new Force(value/1e5); - } #else public static Force FromDyne(QuantityValue dyne) +#endif { double value = (double) dyne; - return new Force((value/1e5)); + return new Force(value, ForceUnit.Dyn); } -#endif /// /// Get Force from KilogramsForce. @@ -260,17 +243,13 @@ public static Force FromDyne(QuantityValue dyne) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Force FromKilogramsForce(double kilogramsforce) - { - double value = (double) kilogramsforce; - return new Force(value*9.80665002864); - } #else public static Force FromKilogramsForce(QuantityValue kilogramsforce) +#endif { double value = (double) kilogramsforce; - return new Force((value*9.80665002864)); + return new Force(value, ForceUnit.KilogramForce); } -#endif /// /// Get Force from Kilonewtons. @@ -278,17 +257,13 @@ public static Force FromKilogramsForce(QuantityValue kilogramsforce) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Force FromKilonewtons(double kilonewtons) - { - double value = (double) kilonewtons; - return new Force((value) * 1e3d); - } #else public static Force FromKilonewtons(QuantityValue kilonewtons) +#endif { double value = (double) kilonewtons; - return new Force(((value) * 1e3d)); + return new Force(value, ForceUnit.Kilonewton); } -#endif /// /// Get Force from KiloPonds. @@ -296,17 +271,13 @@ public static Force FromKilonewtons(QuantityValue kilonewtons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Force FromKiloPonds(double kiloponds) - { - double value = (double) kiloponds; - return new Force(value*9.80665002864); - } #else public static Force FromKiloPonds(QuantityValue kiloponds) +#endif { double value = (double) kiloponds; - return new Force((value*9.80665002864)); + return new Force(value, ForceUnit.KiloPond); } -#endif /// /// Get Force from Meganewtons. @@ -314,17 +285,13 @@ public static Force FromKiloPonds(QuantityValue kiloponds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Force FromMeganewtons(double meganewtons) - { - double value = (double) meganewtons; - return new Force((value) * 1e6d); - } #else public static Force FromMeganewtons(QuantityValue meganewtons) +#endif { double value = (double) meganewtons; - return new Force(((value) * 1e6d)); + return new Force(value, ForceUnit.Meganewton); } -#endif /// /// Get Force from Newtons. @@ -332,17 +299,13 @@ public static Force FromMeganewtons(QuantityValue meganewtons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Force FromNewtons(double newtons) - { - double value = (double) newtons; - return new Force(value); - } #else public static Force FromNewtons(QuantityValue newtons) +#endif { double value = (double) newtons; - return new Force((value)); + return new Force(value, ForceUnit.Newton); } -#endif /// /// Get Force from Poundals. @@ -350,17 +313,13 @@ public static Force FromNewtons(QuantityValue newtons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Force FromPoundals(double poundals) - { - double value = (double) poundals; - return new Force(value*0.13825502798973041652092282466083); - } #else public static Force FromPoundals(QuantityValue poundals) +#endif { double value = (double) poundals; - return new Force((value*0.13825502798973041652092282466083)); + return new Force(value, ForceUnit.Poundal); } -#endif /// /// Get Force from PoundsForce. @@ -368,17 +327,13 @@ public static Force FromPoundals(QuantityValue poundals) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Force FromPoundsForce(double poundsforce) - { - double value = (double) poundsforce; - return new Force(value*4.4482216152605095551842641431421); - } #else public static Force FromPoundsForce(QuantityValue poundsforce) +#endif { double value = (double) poundsforce; - return new Force((value*4.4482216152605095551842641431421)); + return new Force(value, ForceUnit.PoundForce); } -#endif /// /// Get Force from TonnesForce. @@ -386,17 +341,13 @@ public static Force FromPoundsForce(QuantityValue poundsforce) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Force FromTonnesForce(double tonnesforce) - { - double value = (double) tonnesforce; - return new Force(value*9.80665002864*1000); - } #else public static Force FromTonnesForce(QuantityValue tonnesforce) +#endif { double value = (double) tonnesforce; - return new Force((value*9.80665002864*1000)); + return new Force(value, ForceUnit.TonneForce); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -566,32 +517,7 @@ public static Force From(double value, ForceUnit fromUnit) public static Force From(QuantityValue value, ForceUnit fromUnit) #endif { - switch (fromUnit) - { - case ForceUnit.Decanewton: - return FromDecanewtons(value); - case ForceUnit.Dyn: - return FromDyne(value); - case ForceUnit.KilogramForce: - return FromKilogramsForce(value); - case ForceUnit.Kilonewton: - return FromKilonewtons(value); - case ForceUnit.KiloPond: - return FromKiloPonds(value); - case ForceUnit.Meganewton: - return FromMeganewtons(value); - case ForceUnit.Newton: - return FromNewtons(value); - case ForceUnit.Poundal: - return FromPoundals(value); - case ForceUnit.PoundForce: - return FromPoundsForce(value); - case ForceUnit.TonneForce: - return FromTonnesForce(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Force((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -608,32 +534,8 @@ public static Force From(QuantityValue value, ForceUnit fromUnit) { return null; } - switch (fromUnit) - { - case ForceUnit.Decanewton: - return FromDecanewtons(value.Value); - case ForceUnit.Dyn: - return FromDyne(value.Value); - case ForceUnit.KilogramForce: - return FromKilogramsForce(value.Value); - case ForceUnit.Kilonewton: - return FromKilonewtons(value.Value); - case ForceUnit.KiloPond: - return FromKiloPonds(value.Value); - case ForceUnit.Meganewton: - return FromMeganewtons(value.Value); - case ForceUnit.Newton: - return FromNewtons(value.Value); - case ForceUnit.Poundal: - return FromPoundals(value.Value); - case ForceUnit.PoundForce: - return FromPoundsForce(value.Value); - case ForceUnit.TonneForce: - return FromTonnesForce(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Force((double)value.Value, fromUnit); } #endif @@ -652,12 +554,29 @@ public static string GetAbbreviation(ForceUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ForceUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ForceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -668,37 +587,37 @@ public static string GetAbbreviation(ForceUnit unit, [CanBeNull] Culture culture #if !WINDOWS_UWP public static Force operator -(Force right) { - return new Force(-right._newtons); + return new Force(-right.Value, right.Unit); } public static Force operator +(Force left, Force right) { - return new Force(left._newtons + right._newtons); + return new Force(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Force operator -(Force left, Force right) { - return new Force(left._newtons - right._newtons); + return new Force(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Force operator *(double left, Force right) { - return new Force(left*right._newtons); + return new Force(left * right.Value, right.Unit); } public static Force operator *(Force left, double right) { - return new Force(left._newtons*(double)right); + return new Force(left.Value * right, left.Unit); } public static Force operator /(Force left, double right) { - return new Force(left._newtons/(double)right); + return new Force(left.Value / right, left.Unit); } public static double operator /(Force left, Force right) { - return Convert.ToDouble(left._newtons/right._newtons); + return left.Newtons / right.Newtons; } #endif @@ -721,43 +640,43 @@ public int CompareTo(object obj) #endif int CompareTo(Force other) { - return _newtons.CompareTo(other._newtons); + return AsBaseUnitNewtons().CompareTo(other.AsBaseUnitNewtons()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Force left, Force right) { - return left._newtons <= right._newtons; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Force left, Force right) { - return left._newtons >= right._newtons; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Force left, Force right) { - return left._newtons < right._newtons; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Force left, Force right) { - return left._newtons > right._newtons; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Force left, Force right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtons == right._newtons; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Force left, Force right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtons != right._newtons; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -769,7 +688,7 @@ public override bool Equals(object obj) return false; } - return _newtons.Equals(((Force) obj)._newtons); + return AsBaseUnitNewtons().Equals(((Force) obj).AsBaseUnitNewtons()); } /// @@ -782,12 +701,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Force other, Force maxError) { - return Math.Abs(_newtons - other._newtons) <= maxError._newtons; + return Math.Abs(AsBaseUnitNewtons() - other.AsBaseUnitNewtons()) <= maxError.AsBaseUnitNewtons(); } public override int GetHashCode() { - return _newtons.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -797,32 +716,28 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ForceUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitNewtons(); + switch (unit) { - case ForceUnit.Decanewton: - return Decanewtons; - case ForceUnit.Dyn: - return Dyne; - case ForceUnit.KilogramForce: - return KilogramsForce; - case ForceUnit.Kilonewton: - return Kilonewtons; - case ForceUnit.KiloPond: - return KiloPonds; - case ForceUnit.Meganewton: - return Meganewtons; - case ForceUnit.Newton: - return Newtons; - case ForceUnit.Poundal: - return Poundals; - case ForceUnit.PoundForce: - return PoundsForce; - case ForceUnit.TonneForce: - return TonnesForce; + case ForceUnit.Decanewton: return (baseUnitValue) / 1e1d; + case ForceUnit.Dyn: return baseUnitValue*1e5; + case ForceUnit.KilogramForce: return baseUnitValue/9.80665002864; + case ForceUnit.Kilonewton: return (baseUnitValue) / 1e3d; + case ForceUnit.KiloPond: return baseUnitValue/9.80665002864; + case ForceUnit.Meganewton: return (baseUnitValue) / 1e6d; + case ForceUnit.Newton: return baseUnitValue; + case ForceUnit.Poundal: return baseUnitValue/0.13825502798973041652092282466083; + case ForceUnit.PoundForce: return baseUnitValue/4.4482216152605095551842641431421; + case ForceUnit.TonneForce: return baseUnitValue/9.80665002864/1000; default: throw new NotImplementedException("unit: " + unit); @@ -864,7 +779,11 @@ public static Force Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -883,17 +802,24 @@ public static Force Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Force Parse(string str, [CanBeNull] Culture culture) + public static Force Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -919,16 +845,41 @@ public static bool TryParse([CanBeNull] string str, out Force result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Force result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Force result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -941,6 +892,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -954,11 +906,14 @@ public static ForceUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ForceUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -967,6 +922,8 @@ public static ForceUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -979,18 +936,18 @@ public static ForceUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static ForceUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ForceUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ForceUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForceUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -999,6 +956,7 @@ static ForceUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Newton /// @@ -1010,7 +968,7 @@ static ForceUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1027,74 +985,138 @@ public string ToString(ForceUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ForceUnit unit, [CanBeNull] Culture culture) + public string ToString( + ForceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ForceUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ForceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ForceUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ForceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Force /// - public static Force MaxValue - { - get - { - return new Force(double.MaxValue); - } - } + public static Force MaxValue => new Force(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Force /// - public static Force MinValue + public static Force MinValue => new Force(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitNewtons() { - get + if (Unit == ForceUnit.Newton) { return _value; } + + switch (Unit) { - return new Force(double.MinValue); - } - } - } + case ForceUnit.Decanewton: return (_value) * 1e1d; + case ForceUnit.Dyn: return _value/1e5; + case ForceUnit.KilogramForce: return _value*9.80665002864; + case ForceUnit.Kilonewton: return (_value) * 1e3d; + case ForceUnit.KiloPond: return _value*9.80665002864; + case ForceUnit.Meganewton: return (_value) * 1e6d; + case ForceUnit.Newton: return _value; + case ForceUnit.Poundal: return _value*0.13825502798973041652092282466083; + case ForceUnit.PoundForce: return _value*4.4482216152605095551842641431421; + case ForceUnit.TonneForce: return _value*9.80665002864*1000; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ForceUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs index 675eae8800..10a0e8d480 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ForceChangeRate : IComparable, IComparable - /// Base unit of ForceChangeRate. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ForceChangeRateUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _newtonsPerSecond; + public ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ForceChangeRate() : this(0) + public ForceChangeRate() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ForceChangeRate(double newtonspersecond) { - _newtonsPerSecond = Convert.ToDouble(newtonspersecond); + _value = Convert.ToDouble(newtonspersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ForceChangeRate(double numericValue, ForceChangeRateUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit NewtonPerSecond. + /// + /// Value assuming base unit NewtonPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ForceChangeRate(long newtonspersecond) - { - _newtonsPerSecond = Convert.ToDouble(newtonspersecond); - } + ForceChangeRate(long newtonspersecond) : this(Convert.ToDouble(newtonspersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit NewtonPerSecond. + /// + /// Value assuming base unit NewtonPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ForceChangeRate(decimal newtonspersecond) - { - _newtonsPerSecond = Convert.ToDouble(newtonspersecond); - } + ForceChangeRate(decimal newtonspersecond) : this(Convert.ToDouble(newtonspersecond), BaseUnit) { } #region Properties @@ -119,112 +156,62 @@ public ForceChangeRate(double newtonspersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ForceChangeRateUnit BaseUnit - { - get { return ForceChangeRateUnit.NewtonPerSecond; } - } + public static ForceChangeRateUnit BaseUnit => ForceChangeRateUnit.NewtonPerSecond; /// /// All units of measurement for the ForceChangeRate quantity. /// public static ForceChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().ToArray(); - /// /// Get ForceChangeRate in CentinewtonsPerSecond. /// - public double CentinewtonsPerSecond - { - get { return (_newtonsPerSecond) / 1e-2d; } - } - + public double CentinewtonsPerSecond => As(ForceChangeRateUnit.CentinewtonPerSecond); /// /// Get ForceChangeRate in DecanewtonsPerMinute. /// - public double DecanewtonsPerMinute - { - get { return (_newtonsPerSecond*60) / 1e1d; } - } - + public double DecanewtonsPerMinute => As(ForceChangeRateUnit.DecanewtonPerMinute); /// /// Get ForceChangeRate in DecanewtonsPerSecond. /// - public double DecanewtonsPerSecond - { - get { return (_newtonsPerSecond) / 1e1d; } - } - + public double DecanewtonsPerSecond => As(ForceChangeRateUnit.DecanewtonPerSecond); /// /// Get ForceChangeRate in DecinewtonsPerSecond. /// - public double DecinewtonsPerSecond - { - get { return (_newtonsPerSecond) / 1e-1d; } - } - + public double DecinewtonsPerSecond => As(ForceChangeRateUnit.DecinewtonPerSecond); /// /// Get ForceChangeRate in KilonewtonsPerMinute. /// - public double KilonewtonsPerMinute - { - get { return (_newtonsPerSecond*60) / 1e3d; } - } - + public double KilonewtonsPerMinute => As(ForceChangeRateUnit.KilonewtonPerMinute); /// /// Get ForceChangeRate in KilonewtonsPerSecond. /// - public double KilonewtonsPerSecond - { - get { return (_newtonsPerSecond) / 1e3d; } - } - + public double KilonewtonsPerSecond => As(ForceChangeRateUnit.KilonewtonPerSecond); /// /// Get ForceChangeRate in MicronewtonsPerSecond. /// - public double MicronewtonsPerSecond - { - get { return (_newtonsPerSecond) / 1e-6d; } - } - + public double MicronewtonsPerSecond => As(ForceChangeRateUnit.MicronewtonPerSecond); /// /// Get ForceChangeRate in MillinewtonsPerSecond. /// - public double MillinewtonsPerSecond - { - get { return (_newtonsPerSecond) / 1e-3d; } - } - + public double MillinewtonsPerSecond => As(ForceChangeRateUnit.MillinewtonPerSecond); /// /// Get ForceChangeRate in NanonewtonsPerSecond. /// - public double NanonewtonsPerSecond - { - get { return (_newtonsPerSecond) / 1e-9d; } - } - + public double NanonewtonsPerSecond => As(ForceChangeRateUnit.NanonewtonPerSecond); /// /// Get ForceChangeRate in NewtonsPerMinute. /// - public double NewtonsPerMinute - { - get { return _newtonsPerSecond*60; } - } - + public double NewtonsPerMinute => As(ForceChangeRateUnit.NewtonPerMinute); /// /// Get ForceChangeRate in NewtonsPerSecond. /// - public double NewtonsPerSecond - { - get { return _newtonsPerSecond; } - } + public double NewtonsPerSecond => As(ForceChangeRateUnit.NewtonPerSecond); #endregion #region Static - public static ForceChangeRate Zero - { - get { return new ForceChangeRate(); } - } + public static ForceChangeRate Zero => new ForceChangeRate(0, BaseUnit); /// /// Get ForceChangeRate from CentinewtonsPerSecond. @@ -232,17 +219,13 @@ public static ForceChangeRate Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromCentinewtonsPerSecond(double centinewtonspersecond) - { - double value = (double) centinewtonspersecond; - return new ForceChangeRate((value) * 1e-2d); - } #else public static ForceChangeRate FromCentinewtonsPerSecond(QuantityValue centinewtonspersecond) +#endif { double value = (double) centinewtonspersecond; - return new ForceChangeRate(((value) * 1e-2d)); + return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); } -#endif /// /// Get ForceChangeRate from DecanewtonsPerMinute. @@ -250,17 +233,13 @@ public static ForceChangeRate FromCentinewtonsPerSecond(QuantityValue centinewto #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromDecanewtonsPerMinute(double decanewtonsperminute) - { - double value = (double) decanewtonsperminute; - return new ForceChangeRate((value/60) * 1e1d); - } #else public static ForceChangeRate FromDecanewtonsPerMinute(QuantityValue decanewtonsperminute) +#endif { double value = (double) decanewtonsperminute; - return new ForceChangeRate(((value/60) * 1e1d)); + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); } -#endif /// /// Get ForceChangeRate from DecanewtonsPerSecond. @@ -268,17 +247,13 @@ public static ForceChangeRate FromDecanewtonsPerMinute(QuantityValue decanewtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromDecanewtonsPerSecond(double decanewtonspersecond) - { - double value = (double) decanewtonspersecond; - return new ForceChangeRate((value) * 1e1d); - } #else public static ForceChangeRate FromDecanewtonsPerSecond(QuantityValue decanewtonspersecond) +#endif { double value = (double) decanewtonspersecond; - return new ForceChangeRate(((value) * 1e1d)); + return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); } -#endif /// /// Get ForceChangeRate from DecinewtonsPerSecond. @@ -286,17 +261,13 @@ public static ForceChangeRate FromDecanewtonsPerSecond(QuantityValue decanewtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromDecinewtonsPerSecond(double decinewtonspersecond) - { - double value = (double) decinewtonspersecond; - return new ForceChangeRate((value) * 1e-1d); - } #else public static ForceChangeRate FromDecinewtonsPerSecond(QuantityValue decinewtonspersecond) +#endif { double value = (double) decinewtonspersecond; - return new ForceChangeRate(((value) * 1e-1d)); + return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); } -#endif /// /// Get ForceChangeRate from KilonewtonsPerMinute. @@ -304,17 +275,13 @@ public static ForceChangeRate FromDecinewtonsPerSecond(QuantityValue decinewtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromKilonewtonsPerMinute(double kilonewtonsperminute) - { - double value = (double) kilonewtonsperminute; - return new ForceChangeRate((value/60) * 1e3d); - } #else public static ForceChangeRate FromKilonewtonsPerMinute(QuantityValue kilonewtonsperminute) +#endif { double value = (double) kilonewtonsperminute; - return new ForceChangeRate(((value/60) * 1e3d)); + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); } -#endif /// /// Get ForceChangeRate from KilonewtonsPerSecond. @@ -322,17 +289,13 @@ public static ForceChangeRate FromKilonewtonsPerMinute(QuantityValue kilonewtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromKilonewtonsPerSecond(double kilonewtonspersecond) - { - double value = (double) kilonewtonspersecond; - return new ForceChangeRate((value) * 1e3d); - } #else public static ForceChangeRate FromKilonewtonsPerSecond(QuantityValue kilonewtonspersecond) +#endif { double value = (double) kilonewtonspersecond; - return new ForceChangeRate(((value) * 1e3d)); + return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); } -#endif /// /// Get ForceChangeRate from MicronewtonsPerSecond. @@ -340,17 +303,13 @@ public static ForceChangeRate FromKilonewtonsPerSecond(QuantityValue kilonewtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromMicronewtonsPerSecond(double micronewtonspersecond) - { - double value = (double) micronewtonspersecond; - return new ForceChangeRate((value) * 1e-6d); - } #else public static ForceChangeRate FromMicronewtonsPerSecond(QuantityValue micronewtonspersecond) +#endif { double value = (double) micronewtonspersecond; - return new ForceChangeRate(((value) * 1e-6d)); + return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); } -#endif /// /// Get ForceChangeRate from MillinewtonsPerSecond. @@ -358,17 +317,13 @@ public static ForceChangeRate FromMicronewtonsPerSecond(QuantityValue micronewto #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromMillinewtonsPerSecond(double millinewtonspersecond) - { - double value = (double) millinewtonspersecond; - return new ForceChangeRate((value) * 1e-3d); - } #else public static ForceChangeRate FromMillinewtonsPerSecond(QuantityValue millinewtonspersecond) +#endif { double value = (double) millinewtonspersecond; - return new ForceChangeRate(((value) * 1e-3d)); + return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); } -#endif /// /// Get ForceChangeRate from NanonewtonsPerSecond. @@ -376,17 +331,13 @@ public static ForceChangeRate FromMillinewtonsPerSecond(QuantityValue millinewto #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromNanonewtonsPerSecond(double nanonewtonspersecond) - { - double value = (double) nanonewtonspersecond; - return new ForceChangeRate((value) * 1e-9d); - } #else public static ForceChangeRate FromNanonewtonsPerSecond(QuantityValue nanonewtonspersecond) +#endif { double value = (double) nanonewtonspersecond; - return new ForceChangeRate(((value) * 1e-9d)); + return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); } -#endif /// /// Get ForceChangeRate from NewtonsPerMinute. @@ -394,17 +345,13 @@ public static ForceChangeRate FromNanonewtonsPerSecond(QuantityValue nanonewtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromNewtonsPerMinute(double newtonsperminute) - { - double value = (double) newtonsperminute; - return new ForceChangeRate(value/60); - } #else public static ForceChangeRate FromNewtonsPerMinute(QuantityValue newtonsperminute) +#endif { double value = (double) newtonsperminute; - return new ForceChangeRate((value/60)); + return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); } -#endif /// /// Get ForceChangeRate from NewtonsPerSecond. @@ -412,17 +359,13 @@ public static ForceChangeRate FromNewtonsPerMinute(QuantityValue newtonsperminut #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForceChangeRate FromNewtonsPerSecond(double newtonspersecond) - { - double value = (double) newtonspersecond; - return new ForceChangeRate(value); - } #else public static ForceChangeRate FromNewtonsPerSecond(QuantityValue newtonspersecond) +#endif { double value = (double) newtonspersecond; - return new ForceChangeRate((value)); + return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerSecond); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -607,34 +550,7 @@ public static ForceChangeRate From(double value, ForceChangeRateUnit fromUnit) public static ForceChangeRate From(QuantityValue value, ForceChangeRateUnit fromUnit) #endif { - switch (fromUnit) - { - case ForceChangeRateUnit.CentinewtonPerSecond: - return FromCentinewtonsPerSecond(value); - case ForceChangeRateUnit.DecanewtonPerMinute: - return FromDecanewtonsPerMinute(value); - case ForceChangeRateUnit.DecanewtonPerSecond: - return FromDecanewtonsPerSecond(value); - case ForceChangeRateUnit.DecinewtonPerSecond: - return FromDecinewtonsPerSecond(value); - case ForceChangeRateUnit.KilonewtonPerMinute: - return FromKilonewtonsPerMinute(value); - case ForceChangeRateUnit.KilonewtonPerSecond: - return FromKilonewtonsPerSecond(value); - case ForceChangeRateUnit.MicronewtonPerSecond: - return FromMicronewtonsPerSecond(value); - case ForceChangeRateUnit.MillinewtonPerSecond: - return FromMillinewtonsPerSecond(value); - case ForceChangeRateUnit.NanonewtonPerSecond: - return FromNanonewtonsPerSecond(value); - case ForceChangeRateUnit.NewtonPerMinute: - return FromNewtonsPerMinute(value); - case ForceChangeRateUnit.NewtonPerSecond: - return FromNewtonsPerSecond(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ForceChangeRate((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -651,34 +567,8 @@ public static ForceChangeRate From(QuantityValue value, ForceChangeRateUnit from { return null; } - switch (fromUnit) - { - case ForceChangeRateUnit.CentinewtonPerSecond: - return FromCentinewtonsPerSecond(value.Value); - case ForceChangeRateUnit.DecanewtonPerMinute: - return FromDecanewtonsPerMinute(value.Value); - case ForceChangeRateUnit.DecanewtonPerSecond: - return FromDecanewtonsPerSecond(value.Value); - case ForceChangeRateUnit.DecinewtonPerSecond: - return FromDecinewtonsPerSecond(value.Value); - case ForceChangeRateUnit.KilonewtonPerMinute: - return FromKilonewtonsPerMinute(value.Value); - case ForceChangeRateUnit.KilonewtonPerSecond: - return FromKilonewtonsPerSecond(value.Value); - case ForceChangeRateUnit.MicronewtonPerSecond: - return FromMicronewtonsPerSecond(value.Value); - case ForceChangeRateUnit.MillinewtonPerSecond: - return FromMillinewtonsPerSecond(value.Value); - case ForceChangeRateUnit.NanonewtonPerSecond: - return FromNanonewtonsPerSecond(value.Value); - case ForceChangeRateUnit.NewtonPerMinute: - return FromNewtonsPerMinute(value.Value); - case ForceChangeRateUnit.NewtonPerSecond: - return FromNewtonsPerSecond(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ForceChangeRate((double)value.Value, fromUnit); } #endif @@ -697,12 +587,29 @@ public static string GetAbbreviation(ForceChangeRateUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ForceChangeRateUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ForceChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -713,37 +620,37 @@ public static string GetAbbreviation(ForceChangeRateUnit unit, [CanBeNull] Cultu #if !WINDOWS_UWP public static ForceChangeRate operator -(ForceChangeRate right) { - return new ForceChangeRate(-right._newtonsPerSecond); + return new ForceChangeRate(-right.Value, right.Unit); } public static ForceChangeRate operator +(ForceChangeRate left, ForceChangeRate right) { - return new ForceChangeRate(left._newtonsPerSecond + right._newtonsPerSecond); + return new ForceChangeRate(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ForceChangeRate operator -(ForceChangeRate left, ForceChangeRate right) { - return new ForceChangeRate(left._newtonsPerSecond - right._newtonsPerSecond); + return new ForceChangeRate(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ForceChangeRate operator *(double left, ForceChangeRate right) { - return new ForceChangeRate(left*right._newtonsPerSecond); + return new ForceChangeRate(left * right.Value, right.Unit); } public static ForceChangeRate operator *(ForceChangeRate left, double right) { - return new ForceChangeRate(left._newtonsPerSecond*(double)right); + return new ForceChangeRate(left.Value * right, left.Unit); } public static ForceChangeRate operator /(ForceChangeRate left, double right) { - return new ForceChangeRate(left._newtonsPerSecond/(double)right); + return new ForceChangeRate(left.Value / right, left.Unit); } public static double operator /(ForceChangeRate left, ForceChangeRate right) { - return Convert.ToDouble(left._newtonsPerSecond/right._newtonsPerSecond); + return left.NewtonsPerSecond / right.NewtonsPerSecond; } #endif @@ -766,43 +673,43 @@ public int CompareTo(object obj) #endif int CompareTo(ForceChangeRate other) { - return _newtonsPerSecond.CompareTo(other._newtonsPerSecond); + return AsBaseUnitNewtonsPerSecond().CompareTo(other.AsBaseUnitNewtonsPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ForceChangeRate left, ForceChangeRate right) { - return left._newtonsPerSecond <= right._newtonsPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ForceChangeRate left, ForceChangeRate right) { - return left._newtonsPerSecond >= right._newtonsPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ForceChangeRate left, ForceChangeRate right) { - return left._newtonsPerSecond < right._newtonsPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ForceChangeRate left, ForceChangeRate right) { - return left._newtonsPerSecond > right._newtonsPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ForceChangeRate left, ForceChangeRate right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtonsPerSecond == right._newtonsPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ForceChangeRate left, ForceChangeRate right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtonsPerSecond != right._newtonsPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -814,7 +721,7 @@ public override bool Equals(object obj) return false; } - return _newtonsPerSecond.Equals(((ForceChangeRate) obj)._newtonsPerSecond); + return AsBaseUnitNewtonsPerSecond().Equals(((ForceChangeRate) obj).AsBaseUnitNewtonsPerSecond()); } /// @@ -827,12 +734,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ForceChangeRate other, ForceChangeRate maxError) { - return Math.Abs(_newtonsPerSecond - other._newtonsPerSecond) <= maxError._newtonsPerSecond; + return Math.Abs(AsBaseUnitNewtonsPerSecond() - other.AsBaseUnitNewtonsPerSecond()) <= maxError.AsBaseUnitNewtonsPerSecond(); } public override int GetHashCode() { - return _newtonsPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -842,34 +749,29 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ForceChangeRateUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitNewtonsPerSecond(); + switch (unit) { - case ForceChangeRateUnit.CentinewtonPerSecond: - return CentinewtonsPerSecond; - case ForceChangeRateUnit.DecanewtonPerMinute: - return DecanewtonsPerMinute; - case ForceChangeRateUnit.DecanewtonPerSecond: - return DecanewtonsPerSecond; - case ForceChangeRateUnit.DecinewtonPerSecond: - return DecinewtonsPerSecond; - case ForceChangeRateUnit.KilonewtonPerMinute: - return KilonewtonsPerMinute; - case ForceChangeRateUnit.KilonewtonPerSecond: - return KilonewtonsPerSecond; - case ForceChangeRateUnit.MicronewtonPerSecond: - return MicronewtonsPerSecond; - case ForceChangeRateUnit.MillinewtonPerSecond: - return MillinewtonsPerSecond; - case ForceChangeRateUnit.NanonewtonPerSecond: - return NanonewtonsPerSecond; - case ForceChangeRateUnit.NewtonPerMinute: - return NewtonsPerMinute; - case ForceChangeRateUnit.NewtonPerSecond: - return NewtonsPerSecond; + case ForceChangeRateUnit.CentinewtonPerSecond: return (baseUnitValue) / 1e-2d; + case ForceChangeRateUnit.DecanewtonPerMinute: return (baseUnitValue*60) / 1e1d; + case ForceChangeRateUnit.DecanewtonPerSecond: return (baseUnitValue) / 1e1d; + case ForceChangeRateUnit.DecinewtonPerSecond: return (baseUnitValue) / 1e-1d; + case ForceChangeRateUnit.KilonewtonPerMinute: return (baseUnitValue*60) / 1e3d; + case ForceChangeRateUnit.KilonewtonPerSecond: return (baseUnitValue) / 1e3d; + case ForceChangeRateUnit.MicronewtonPerSecond: return (baseUnitValue) / 1e-6d; + case ForceChangeRateUnit.MillinewtonPerSecond: return (baseUnitValue) / 1e-3d; + case ForceChangeRateUnit.NanonewtonPerSecond: return (baseUnitValue) / 1e-9d; + case ForceChangeRateUnit.NewtonPerMinute: return baseUnitValue*60; + case ForceChangeRateUnit.NewtonPerSecond: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -911,7 +813,11 @@ public static ForceChangeRate Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -930,17 +836,24 @@ public static ForceChangeRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ForceChangeRate Parse(string str, [CanBeNull] Culture culture) + public static ForceChangeRate Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -966,16 +879,41 @@ public static bool TryParse([CanBeNull] string str, out ForceChangeRate result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ForceChangeRate result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ForceChangeRate result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -988,6 +926,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1001,11 +940,14 @@ public static ForceChangeRateUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ForceChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1014,6 +956,8 @@ public static ForceChangeRateUnit ParseUnit(string str, [CanBeNull] string cultu /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1026,18 +970,18 @@ public static ForceChangeRateUnit ParseUnit(string str, [CanBeNull] string cultu #else public #endif - static ForceChangeRateUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ForceChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ForceChangeRateUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForceChangeRateUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1046,6 +990,7 @@ static ForceChangeRateUnit ParseUnit(string str, IFormatProvider formatProvider #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is NewtonPerSecond /// @@ -1057,7 +1002,7 @@ static ForceChangeRateUnit ParseUnit(string str, IFormatProvider formatProvider /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1074,74 +1019,139 @@ public string ToString(ForceChangeRateUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ForceChangeRateUnit unit, [CanBeNull] Culture culture) + public string ToString( + ForceChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ForceChangeRateUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ForceChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ForceChangeRateUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ForceChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ForceChangeRate /// - public static ForceChangeRate MaxValue - { - get - { - return new ForceChangeRate(double.MaxValue); - } - } + public static ForceChangeRate MaxValue => new ForceChangeRate(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ForceChangeRate /// - public static ForceChangeRate MinValue + public static ForceChangeRate MinValue => new ForceChangeRate(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitNewtonsPerSecond() { - get + if (Unit == ForceChangeRateUnit.NewtonPerSecond) { return _value; } + + switch (Unit) { - return new ForceChangeRate(double.MinValue); - } - } - } + case ForceChangeRateUnit.CentinewtonPerSecond: return (_value) * 1e-2d; + case ForceChangeRateUnit.DecanewtonPerMinute: return (_value/60) * 1e1d; + case ForceChangeRateUnit.DecanewtonPerSecond: return (_value) * 1e1d; + case ForceChangeRateUnit.DecinewtonPerSecond: return (_value) * 1e-1d; + case ForceChangeRateUnit.KilonewtonPerMinute: return (_value/60) * 1e3d; + case ForceChangeRateUnit.KilonewtonPerSecond: return (_value) * 1e3d; + case ForceChangeRateUnit.MicronewtonPerSecond: return (_value) * 1e-6d; + case ForceChangeRateUnit.MillinewtonPerSecond: return (_value) * 1e-3d; + case ForceChangeRateUnit.NanonewtonPerSecond: return (_value) * 1e-9d; + case ForceChangeRateUnit.NewtonPerMinute: return _value/60; + case ForceChangeRateUnit.NewtonPerSecond: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ForceChangeRateUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs index 932fe9849c..27a5af6e23 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ForcePerLength : IComparable, IComparable #endif { /// - /// Base unit of ForcePerLength. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ForcePerLengthUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _newtonsPerMeter; + public ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ForcePerLength() : this(0) + public ForcePerLength() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ForcePerLength(double newtonspermeter) { - _newtonsPerMeter = Convert.ToDouble(newtonspermeter); + _value = Convert.ToDouble(newtonspermeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ForcePerLength(double numericValue, ForcePerLengthUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit NewtonPerMeter. + /// + /// Value assuming base unit NewtonPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ForcePerLength(long newtonspermeter) - { - _newtonsPerMeter = Convert.ToDouble(newtonspermeter); - } + ForcePerLength(long newtonspermeter) : this(Convert.ToDouble(newtonspermeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit NewtonPerMeter. + /// + /// Value assuming base unit NewtonPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ForcePerLength(decimal newtonspermeter) - { - _newtonsPerMeter = Convert.ToDouble(newtonspermeter); - } + ForcePerLength(decimal newtonspermeter) : this(Convert.ToDouble(newtonspermeter), BaseUnit) { } #region Properties @@ -119,96 +156,54 @@ public ForcePerLength(double newtonspermeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ForcePerLengthUnit BaseUnit - { - get { return ForcePerLengthUnit.NewtonPerMeter; } - } + public static ForcePerLengthUnit BaseUnit => ForcePerLengthUnit.NewtonPerMeter; /// /// All units of measurement for the ForcePerLength quantity. /// public static ForcePerLengthUnit[] Units { get; } = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().ToArray(); - /// /// Get ForcePerLength in CentinewtonsPerMeter. /// - public double CentinewtonsPerMeter - { - get { return (_newtonsPerMeter) / 1e-2d; } - } - + public double CentinewtonsPerMeter => As(ForcePerLengthUnit.CentinewtonPerMeter); /// /// Get ForcePerLength in DecinewtonsPerMeter. /// - public double DecinewtonsPerMeter - { - get { return (_newtonsPerMeter) / 1e-1d; } - } - + public double DecinewtonsPerMeter => As(ForcePerLengthUnit.DecinewtonPerMeter); /// /// Get ForcePerLength in KilogramsForcePerMeter. /// - public double KilogramsForcePerMeter - { - get { return _newtonsPerMeter/9.80665002864; } - } - + public double KilogramsForcePerMeter => As(ForcePerLengthUnit.KilogramForcePerMeter); /// /// Get ForcePerLength in KilonewtonsPerMeter. /// - public double KilonewtonsPerMeter - { - get { return (_newtonsPerMeter) / 1e3d; } - } - + public double KilonewtonsPerMeter => As(ForcePerLengthUnit.KilonewtonPerMeter); /// /// Get ForcePerLength in MeganewtonsPerMeter. /// - public double MeganewtonsPerMeter - { - get { return (_newtonsPerMeter) / 1e6d; } - } - + public double MeganewtonsPerMeter => As(ForcePerLengthUnit.MeganewtonPerMeter); /// /// Get ForcePerLength in MicronewtonsPerMeter. /// - public double MicronewtonsPerMeter - { - get { return (_newtonsPerMeter) / 1e-6d; } - } - + public double MicronewtonsPerMeter => As(ForcePerLengthUnit.MicronewtonPerMeter); /// /// Get ForcePerLength in MillinewtonsPerMeter. /// - public double MillinewtonsPerMeter - { - get { return (_newtonsPerMeter) / 1e-3d; } - } - + public double MillinewtonsPerMeter => As(ForcePerLengthUnit.MillinewtonPerMeter); /// /// Get ForcePerLength in NanonewtonsPerMeter. /// - public double NanonewtonsPerMeter - { - get { return (_newtonsPerMeter) / 1e-9d; } - } - + public double NanonewtonsPerMeter => As(ForcePerLengthUnit.NanonewtonPerMeter); /// /// Get ForcePerLength in NewtonsPerMeter. /// - public double NewtonsPerMeter - { - get { return _newtonsPerMeter; } - } + public double NewtonsPerMeter => As(ForcePerLengthUnit.NewtonPerMeter); #endregion #region Static - public static ForcePerLength Zero - { - get { return new ForcePerLength(); } - } + public static ForcePerLength Zero => new ForcePerLength(0, BaseUnit); /// /// Get ForcePerLength from CentinewtonsPerMeter. @@ -216,17 +211,13 @@ public static ForcePerLength Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForcePerLength FromCentinewtonsPerMeter(double centinewtonspermeter) - { - double value = (double) centinewtonspermeter; - return new ForcePerLength((value) * 1e-2d); - } #else public static ForcePerLength FromCentinewtonsPerMeter(QuantityValue centinewtonspermeter) +#endif { double value = (double) centinewtonspermeter; - return new ForcePerLength(((value) * 1e-2d)); + return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); } -#endif /// /// Get ForcePerLength from DecinewtonsPerMeter. @@ -234,17 +225,13 @@ public static ForcePerLength FromCentinewtonsPerMeter(QuantityValue centinewtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForcePerLength FromDecinewtonsPerMeter(double decinewtonspermeter) - { - double value = (double) decinewtonspermeter; - return new ForcePerLength((value) * 1e-1d); - } #else public static ForcePerLength FromDecinewtonsPerMeter(QuantityValue decinewtonspermeter) +#endif { double value = (double) decinewtonspermeter; - return new ForcePerLength(((value) * 1e-1d)); + return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); } -#endif /// /// Get ForcePerLength from KilogramsForcePerMeter. @@ -252,17 +239,13 @@ public static ForcePerLength FromDecinewtonsPerMeter(QuantityValue decinewtonspe #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForcePerLength FromKilogramsForcePerMeter(double kilogramsforcepermeter) - { - double value = (double) kilogramsforcepermeter; - return new ForcePerLength(value*9.80665002864); - } #else public static ForcePerLength FromKilogramsForcePerMeter(QuantityValue kilogramsforcepermeter) +#endif { double value = (double) kilogramsforcepermeter; - return new ForcePerLength((value*9.80665002864)); + return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); } -#endif /// /// Get ForcePerLength from KilonewtonsPerMeter. @@ -270,17 +253,13 @@ public static ForcePerLength FromKilogramsForcePerMeter(QuantityValue kilogramsf #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForcePerLength FromKilonewtonsPerMeter(double kilonewtonspermeter) - { - double value = (double) kilonewtonspermeter; - return new ForcePerLength((value) * 1e3d); - } #else public static ForcePerLength FromKilonewtonsPerMeter(QuantityValue kilonewtonspermeter) +#endif { double value = (double) kilonewtonspermeter; - return new ForcePerLength(((value) * 1e3d)); + return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); } -#endif /// /// Get ForcePerLength from MeganewtonsPerMeter. @@ -288,17 +267,13 @@ public static ForcePerLength FromKilonewtonsPerMeter(QuantityValue kilonewtonspe #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForcePerLength FromMeganewtonsPerMeter(double meganewtonspermeter) - { - double value = (double) meganewtonspermeter; - return new ForcePerLength((value) * 1e6d); - } #else public static ForcePerLength FromMeganewtonsPerMeter(QuantityValue meganewtonspermeter) +#endif { double value = (double) meganewtonspermeter; - return new ForcePerLength(((value) * 1e6d)); + return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); } -#endif /// /// Get ForcePerLength from MicronewtonsPerMeter. @@ -306,17 +281,13 @@ public static ForcePerLength FromMeganewtonsPerMeter(QuantityValue meganewtonspe #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForcePerLength FromMicronewtonsPerMeter(double micronewtonspermeter) - { - double value = (double) micronewtonspermeter; - return new ForcePerLength((value) * 1e-6d); - } #else public static ForcePerLength FromMicronewtonsPerMeter(QuantityValue micronewtonspermeter) +#endif { double value = (double) micronewtonspermeter; - return new ForcePerLength(((value) * 1e-6d)); + return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); } -#endif /// /// Get ForcePerLength from MillinewtonsPerMeter. @@ -324,17 +295,13 @@ public static ForcePerLength FromMicronewtonsPerMeter(QuantityValue micronewtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForcePerLength FromMillinewtonsPerMeter(double millinewtonspermeter) - { - double value = (double) millinewtonspermeter; - return new ForcePerLength((value) * 1e-3d); - } #else public static ForcePerLength FromMillinewtonsPerMeter(QuantityValue millinewtonspermeter) +#endif { double value = (double) millinewtonspermeter; - return new ForcePerLength(((value) * 1e-3d)); + return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); } -#endif /// /// Get ForcePerLength from NanonewtonsPerMeter. @@ -342,17 +309,13 @@ public static ForcePerLength FromMillinewtonsPerMeter(QuantityValue millinewtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForcePerLength FromNanonewtonsPerMeter(double nanonewtonspermeter) - { - double value = (double) nanonewtonspermeter; - return new ForcePerLength((value) * 1e-9d); - } #else public static ForcePerLength FromNanonewtonsPerMeter(QuantityValue nanonewtonspermeter) +#endif { double value = (double) nanonewtonspermeter; - return new ForcePerLength(((value) * 1e-9d)); + return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); } -#endif /// /// Get ForcePerLength from NewtonsPerMeter. @@ -360,17 +323,13 @@ public static ForcePerLength FromNanonewtonsPerMeter(QuantityValue nanonewtonspe #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ForcePerLength FromNewtonsPerMeter(double newtonspermeter) - { - double value = (double) newtonspermeter; - return new ForcePerLength(value); - } #else public static ForcePerLength FromNewtonsPerMeter(QuantityValue newtonspermeter) +#endif { double value = (double) newtonspermeter; - return new ForcePerLength((value)); + return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -525,30 +484,7 @@ public static ForcePerLength From(double value, ForcePerLengthUnit fromUnit) public static ForcePerLength From(QuantityValue value, ForcePerLengthUnit fromUnit) #endif { - switch (fromUnit) - { - case ForcePerLengthUnit.CentinewtonPerMeter: - return FromCentinewtonsPerMeter(value); - case ForcePerLengthUnit.DecinewtonPerMeter: - return FromDecinewtonsPerMeter(value); - case ForcePerLengthUnit.KilogramForcePerMeter: - return FromKilogramsForcePerMeter(value); - case ForcePerLengthUnit.KilonewtonPerMeter: - return FromKilonewtonsPerMeter(value); - case ForcePerLengthUnit.MeganewtonPerMeter: - return FromMeganewtonsPerMeter(value); - case ForcePerLengthUnit.MicronewtonPerMeter: - return FromMicronewtonsPerMeter(value); - case ForcePerLengthUnit.MillinewtonPerMeter: - return FromMillinewtonsPerMeter(value); - case ForcePerLengthUnit.NanonewtonPerMeter: - return FromNanonewtonsPerMeter(value); - case ForcePerLengthUnit.NewtonPerMeter: - return FromNewtonsPerMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ForcePerLength((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -565,30 +501,8 @@ public static ForcePerLength From(QuantityValue value, ForcePerLengthUnit fromUn { return null; } - switch (fromUnit) - { - case ForcePerLengthUnit.CentinewtonPerMeter: - return FromCentinewtonsPerMeter(value.Value); - case ForcePerLengthUnit.DecinewtonPerMeter: - return FromDecinewtonsPerMeter(value.Value); - case ForcePerLengthUnit.KilogramForcePerMeter: - return FromKilogramsForcePerMeter(value.Value); - case ForcePerLengthUnit.KilonewtonPerMeter: - return FromKilonewtonsPerMeter(value.Value); - case ForcePerLengthUnit.MeganewtonPerMeter: - return FromMeganewtonsPerMeter(value.Value); - case ForcePerLengthUnit.MicronewtonPerMeter: - return FromMicronewtonsPerMeter(value.Value); - case ForcePerLengthUnit.MillinewtonPerMeter: - return FromMillinewtonsPerMeter(value.Value); - case ForcePerLengthUnit.NanonewtonPerMeter: - return FromNanonewtonsPerMeter(value.Value); - case ForcePerLengthUnit.NewtonPerMeter: - return FromNewtonsPerMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ForcePerLength((double)value.Value, fromUnit); } #endif @@ -607,12 +521,29 @@ public static string GetAbbreviation(ForcePerLengthUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ForcePerLengthUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ForcePerLengthUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -623,37 +554,37 @@ public static string GetAbbreviation(ForcePerLengthUnit unit, [CanBeNull] Cultur #if !WINDOWS_UWP public static ForcePerLength operator -(ForcePerLength right) { - return new ForcePerLength(-right._newtonsPerMeter); + return new ForcePerLength(-right.Value, right.Unit); } public static ForcePerLength operator +(ForcePerLength left, ForcePerLength right) { - return new ForcePerLength(left._newtonsPerMeter + right._newtonsPerMeter); + return new ForcePerLength(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ForcePerLength operator -(ForcePerLength left, ForcePerLength right) { - return new ForcePerLength(left._newtonsPerMeter - right._newtonsPerMeter); + return new ForcePerLength(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ForcePerLength operator *(double left, ForcePerLength right) { - return new ForcePerLength(left*right._newtonsPerMeter); + return new ForcePerLength(left * right.Value, right.Unit); } public static ForcePerLength operator *(ForcePerLength left, double right) { - return new ForcePerLength(left._newtonsPerMeter*(double)right); + return new ForcePerLength(left.Value * right, left.Unit); } public static ForcePerLength operator /(ForcePerLength left, double right) { - return new ForcePerLength(left._newtonsPerMeter/(double)right); + return new ForcePerLength(left.Value / right, left.Unit); } public static double operator /(ForcePerLength left, ForcePerLength right) { - return Convert.ToDouble(left._newtonsPerMeter/right._newtonsPerMeter); + return left.NewtonsPerMeter / right.NewtonsPerMeter; } #endif @@ -676,43 +607,43 @@ public int CompareTo(object obj) #endif int CompareTo(ForcePerLength other) { - return _newtonsPerMeter.CompareTo(other._newtonsPerMeter); + return AsBaseUnitNewtonsPerMeter().CompareTo(other.AsBaseUnitNewtonsPerMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ForcePerLength left, ForcePerLength right) { - return left._newtonsPerMeter <= right._newtonsPerMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ForcePerLength left, ForcePerLength right) { - return left._newtonsPerMeter >= right._newtonsPerMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ForcePerLength left, ForcePerLength right) { - return left._newtonsPerMeter < right._newtonsPerMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ForcePerLength left, ForcePerLength right) { - return left._newtonsPerMeter > right._newtonsPerMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ForcePerLength left, ForcePerLength right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtonsPerMeter == right._newtonsPerMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ForcePerLength left, ForcePerLength right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtonsPerMeter != right._newtonsPerMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -724,7 +655,7 @@ public override bool Equals(object obj) return false; } - return _newtonsPerMeter.Equals(((ForcePerLength) obj)._newtonsPerMeter); + return AsBaseUnitNewtonsPerMeter().Equals(((ForcePerLength) obj).AsBaseUnitNewtonsPerMeter()); } /// @@ -737,12 +668,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ForcePerLength other, ForcePerLength maxError) { - return Math.Abs(_newtonsPerMeter - other._newtonsPerMeter) <= maxError._newtonsPerMeter; + return Math.Abs(AsBaseUnitNewtonsPerMeter() - other.AsBaseUnitNewtonsPerMeter()) <= maxError.AsBaseUnitNewtonsPerMeter(); } public override int GetHashCode() { - return _newtonsPerMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -752,30 +683,27 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ForcePerLengthUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitNewtonsPerMeter(); + switch (unit) { - case ForcePerLengthUnit.CentinewtonPerMeter: - return CentinewtonsPerMeter; - case ForcePerLengthUnit.DecinewtonPerMeter: - return DecinewtonsPerMeter; - case ForcePerLengthUnit.KilogramForcePerMeter: - return KilogramsForcePerMeter; - case ForcePerLengthUnit.KilonewtonPerMeter: - return KilonewtonsPerMeter; - case ForcePerLengthUnit.MeganewtonPerMeter: - return MeganewtonsPerMeter; - case ForcePerLengthUnit.MicronewtonPerMeter: - return MicronewtonsPerMeter; - case ForcePerLengthUnit.MillinewtonPerMeter: - return MillinewtonsPerMeter; - case ForcePerLengthUnit.NanonewtonPerMeter: - return NanonewtonsPerMeter; - case ForcePerLengthUnit.NewtonPerMeter: - return NewtonsPerMeter; + case ForcePerLengthUnit.CentinewtonPerMeter: return (baseUnitValue) / 1e-2d; + case ForcePerLengthUnit.DecinewtonPerMeter: return (baseUnitValue) / 1e-1d; + case ForcePerLengthUnit.KilogramForcePerMeter: return baseUnitValue/9.80665002864; + case ForcePerLengthUnit.KilonewtonPerMeter: return (baseUnitValue) / 1e3d; + case ForcePerLengthUnit.MeganewtonPerMeter: return (baseUnitValue) / 1e6d; + case ForcePerLengthUnit.MicronewtonPerMeter: return (baseUnitValue) / 1e-6d; + case ForcePerLengthUnit.MillinewtonPerMeter: return (baseUnitValue) / 1e-3d; + case ForcePerLengthUnit.NanonewtonPerMeter: return (baseUnitValue) / 1e-9d; + case ForcePerLengthUnit.NewtonPerMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -817,7 +745,11 @@ public static ForcePerLength Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -836,17 +768,24 @@ public static ForcePerLength Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ForcePerLength Parse(string str, [CanBeNull] Culture culture) + public static ForcePerLength Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -872,16 +811,41 @@ public static bool TryParse([CanBeNull] string str, out ForcePerLength result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ForcePerLength result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ForcePerLength result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -894,6 +858,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -907,11 +872,14 @@ public static ForcePerLengthUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ForcePerLengthUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -920,6 +888,8 @@ public static ForcePerLengthUnit ParseUnit(string str, [CanBeNull] string cultur /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -932,18 +902,18 @@ public static ForcePerLengthUnit ParseUnit(string str, [CanBeNull] string cultur #else public #endif - static ForcePerLengthUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ForcePerLengthUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ForcePerLengthUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ForcePerLengthUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -952,6 +922,7 @@ static ForcePerLengthUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is NewtonPerMeter /// @@ -963,7 +934,7 @@ static ForcePerLengthUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -980,74 +951,137 @@ public string ToString(ForcePerLengthUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ForcePerLengthUnit unit, [CanBeNull] Culture culture) + public string ToString( + ForcePerLengthUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ForcePerLengthUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ForcePerLengthUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ForcePerLengthUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ForcePerLengthUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ForcePerLength /// - public static ForcePerLength MaxValue - { - get - { - return new ForcePerLength(double.MaxValue); - } - } + public static ForcePerLength MaxValue => new ForcePerLength(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ForcePerLength /// - public static ForcePerLength MinValue + public static ForcePerLength MinValue => new ForcePerLength(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitNewtonsPerMeter() { - get + if (Unit == ForcePerLengthUnit.NewtonPerMeter) { return _value; } + + switch (Unit) { - return new ForcePerLength(double.MinValue); - } - } - } + case ForcePerLengthUnit.CentinewtonPerMeter: return (_value) * 1e-2d; + case ForcePerLengthUnit.DecinewtonPerMeter: return (_value) * 1e-1d; + case ForcePerLengthUnit.KilogramForcePerMeter: return _value*9.80665002864; + case ForcePerLengthUnit.KilonewtonPerMeter: return (_value) * 1e3d; + case ForcePerLengthUnit.MeganewtonPerMeter: return (_value) * 1e6d; + case ForcePerLengthUnit.MicronewtonPerMeter: return (_value) * 1e-6d; + case ForcePerLengthUnit.MillinewtonPerMeter: return (_value) * 1e-3d; + case ForcePerLengthUnit.NanonewtonPerMeter: return (_value) * 1e-9d; + case ForcePerLengthUnit.NewtonPerMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ForcePerLengthUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs index 13faf4609a..1180a7e209 100644 --- a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Frequency : IComparable, IComparable #endif { /// - /// Base unit of Frequency. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _hertz; + private readonly FrequencyUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Frequency() : this(0) + public Frequency() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Frequency(double hertz) { - _hertz = Convert.ToDouble(hertz); + _value = Convert.ToDouble(hertz); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Frequency(double numericValue, FrequencyUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Hertz. + /// + /// Value assuming base unit Hertz. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Frequency(long hertz) - { - _hertz = Convert.ToDouble(hertz); - } + Frequency(long hertz) : this(Convert.ToDouble(hertz), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Hertz. + /// + /// Value assuming base unit Hertz. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Frequency(decimal hertz) - { - _hertz = Convert.ToDouble(hertz); - } + Frequency(decimal hertz) : this(Convert.ToDouble(hertz), BaseUnit) { } #region Properties @@ -119,88 +156,50 @@ public Frequency(double hertz) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static FrequencyUnit BaseUnit - { - get { return FrequencyUnit.Hertz; } - } + public static FrequencyUnit BaseUnit => FrequencyUnit.Hertz; /// /// All units of measurement for the Frequency quantity. /// public static FrequencyUnit[] Units { get; } = Enum.GetValues(typeof(FrequencyUnit)).Cast().ToArray(); - /// /// Get Frequency in CyclesPerHour. /// - public double CyclesPerHour - { - get { return _hertz*3600; } - } - + public double CyclesPerHour => As(FrequencyUnit.CyclePerHour); /// /// Get Frequency in CyclesPerMinute. /// - public double CyclesPerMinute - { - get { return _hertz*60; } - } - + public double CyclesPerMinute => As(FrequencyUnit.CyclePerMinute); /// /// Get Frequency in Gigahertz. /// - public double Gigahertz - { - get { return (_hertz) / 1e9d; } - } - + public double Gigahertz => As(FrequencyUnit.Gigahertz); /// /// Get Frequency in Hertz. /// - public double Hertz - { - get { return _hertz; } - } - + public double Hertz => As(FrequencyUnit.Hertz); /// /// Get Frequency in Kilohertz. /// - public double Kilohertz - { - get { return (_hertz) / 1e3d; } - } - + public double Kilohertz => As(FrequencyUnit.Kilohertz); /// /// Get Frequency in Megahertz. /// - public double Megahertz - { - get { return (_hertz) / 1e6d; } - } - + public double Megahertz => As(FrequencyUnit.Megahertz); /// /// Get Frequency in RadiansPerSecond. /// - public double RadiansPerSecond - { - get { return _hertz*6.2831853072; } - } - + public double RadiansPerSecond => As(FrequencyUnit.RadianPerSecond); /// /// Get Frequency in Terahertz. /// - public double Terahertz - { - get { return (_hertz) / 1e12d; } - } + public double Terahertz => As(FrequencyUnit.Terahertz); #endregion #region Static - public static Frequency Zero - { - get { return new Frequency(); } - } + public static Frequency Zero => new Frequency(0, BaseUnit); /// /// Get Frequency from CyclesPerHour. @@ -208,17 +207,13 @@ public static Frequency Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Frequency FromCyclesPerHour(double cyclesperhour) - { - double value = (double) cyclesperhour; - return new Frequency(value/3600); - } #else public static Frequency FromCyclesPerHour(QuantityValue cyclesperhour) +#endif { double value = (double) cyclesperhour; - return new Frequency((value/3600)); + return new Frequency(value, FrequencyUnit.CyclePerHour); } -#endif /// /// Get Frequency from CyclesPerMinute. @@ -226,17 +221,13 @@ public static Frequency FromCyclesPerHour(QuantityValue cyclesperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Frequency FromCyclesPerMinute(double cyclesperminute) - { - double value = (double) cyclesperminute; - return new Frequency(value/60); - } #else public static Frequency FromCyclesPerMinute(QuantityValue cyclesperminute) +#endif { double value = (double) cyclesperminute; - return new Frequency((value/60)); + return new Frequency(value, FrequencyUnit.CyclePerMinute); } -#endif /// /// Get Frequency from Gigahertz. @@ -244,17 +235,13 @@ public static Frequency FromCyclesPerMinute(QuantityValue cyclesperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Frequency FromGigahertz(double gigahertz) - { - double value = (double) gigahertz; - return new Frequency((value) * 1e9d); - } #else public static Frequency FromGigahertz(QuantityValue gigahertz) +#endif { double value = (double) gigahertz; - return new Frequency(((value) * 1e9d)); + return new Frequency(value, FrequencyUnit.Gigahertz); } -#endif /// /// Get Frequency from Hertz. @@ -262,17 +249,13 @@ public static Frequency FromGigahertz(QuantityValue gigahertz) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Frequency FromHertz(double hertz) - { - double value = (double) hertz; - return new Frequency(value); - } #else public static Frequency FromHertz(QuantityValue hertz) +#endif { double value = (double) hertz; - return new Frequency((value)); + return new Frequency(value, FrequencyUnit.Hertz); } -#endif /// /// Get Frequency from Kilohertz. @@ -280,17 +263,13 @@ public static Frequency FromHertz(QuantityValue hertz) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Frequency FromKilohertz(double kilohertz) - { - double value = (double) kilohertz; - return new Frequency((value) * 1e3d); - } #else public static Frequency FromKilohertz(QuantityValue kilohertz) +#endif { double value = (double) kilohertz; - return new Frequency(((value) * 1e3d)); + return new Frequency(value, FrequencyUnit.Kilohertz); } -#endif /// /// Get Frequency from Megahertz. @@ -298,17 +277,13 @@ public static Frequency FromKilohertz(QuantityValue kilohertz) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Frequency FromMegahertz(double megahertz) - { - double value = (double) megahertz; - return new Frequency((value) * 1e6d); - } #else public static Frequency FromMegahertz(QuantityValue megahertz) +#endif { double value = (double) megahertz; - return new Frequency(((value) * 1e6d)); + return new Frequency(value, FrequencyUnit.Megahertz); } -#endif /// /// Get Frequency from RadiansPerSecond. @@ -316,17 +291,13 @@ public static Frequency FromMegahertz(QuantityValue megahertz) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Frequency FromRadiansPerSecond(double radianspersecond) - { - double value = (double) radianspersecond; - return new Frequency(value/6.2831853072); - } #else public static Frequency FromRadiansPerSecond(QuantityValue radianspersecond) +#endif { double value = (double) radianspersecond; - return new Frequency((value/6.2831853072)); + return new Frequency(value, FrequencyUnit.RadianPerSecond); } -#endif /// /// Get Frequency from Terahertz. @@ -334,17 +305,13 @@ public static Frequency FromRadiansPerSecond(QuantityValue radianspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Frequency FromTerahertz(double terahertz) - { - double value = (double) terahertz; - return new Frequency((value) * 1e12d); - } #else public static Frequency FromTerahertz(QuantityValue terahertz) +#endif { double value = (double) terahertz; - return new Frequency(((value) * 1e12d)); + return new Frequency(value, FrequencyUnit.Terahertz); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -484,28 +451,7 @@ public static Frequency From(double value, FrequencyUnit fromUnit) public static Frequency From(QuantityValue value, FrequencyUnit fromUnit) #endif { - switch (fromUnit) - { - case FrequencyUnit.CyclePerHour: - return FromCyclesPerHour(value); - case FrequencyUnit.CyclePerMinute: - return FromCyclesPerMinute(value); - case FrequencyUnit.Gigahertz: - return FromGigahertz(value); - case FrequencyUnit.Hertz: - return FromHertz(value); - case FrequencyUnit.Kilohertz: - return FromKilohertz(value); - case FrequencyUnit.Megahertz: - return FromMegahertz(value); - case FrequencyUnit.RadianPerSecond: - return FromRadiansPerSecond(value); - case FrequencyUnit.Terahertz: - return FromTerahertz(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Frequency((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -522,28 +468,8 @@ public static Frequency From(QuantityValue value, FrequencyUnit fromUnit) { return null; } - switch (fromUnit) - { - case FrequencyUnit.CyclePerHour: - return FromCyclesPerHour(value.Value); - case FrequencyUnit.CyclePerMinute: - return FromCyclesPerMinute(value.Value); - case FrequencyUnit.Gigahertz: - return FromGigahertz(value.Value); - case FrequencyUnit.Hertz: - return FromHertz(value.Value); - case FrequencyUnit.Kilohertz: - return FromKilohertz(value.Value); - case FrequencyUnit.Megahertz: - return FromMegahertz(value.Value); - case FrequencyUnit.RadianPerSecond: - return FromRadiansPerSecond(value.Value); - case FrequencyUnit.Terahertz: - return FromTerahertz(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Frequency((double)value.Value, fromUnit); } #endif @@ -562,12 +488,29 @@ public static string GetAbbreviation(FrequencyUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(FrequencyUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + FrequencyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -578,37 +521,37 @@ public static string GetAbbreviation(FrequencyUnit unit, [CanBeNull] Culture cul #if !WINDOWS_UWP public static Frequency operator -(Frequency right) { - return new Frequency(-right._hertz); + return new Frequency(-right.Value, right.Unit); } public static Frequency operator +(Frequency left, Frequency right) { - return new Frequency(left._hertz + right._hertz); + return new Frequency(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Frequency operator -(Frequency left, Frequency right) { - return new Frequency(left._hertz - right._hertz); + return new Frequency(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Frequency operator *(double left, Frequency right) { - return new Frequency(left*right._hertz); + return new Frequency(left * right.Value, right.Unit); } public static Frequency operator *(Frequency left, double right) { - return new Frequency(left._hertz*(double)right); + return new Frequency(left.Value * right, left.Unit); } public static Frequency operator /(Frequency left, double right) { - return new Frequency(left._hertz/(double)right); + return new Frequency(left.Value / right, left.Unit); } public static double operator /(Frequency left, Frequency right) { - return Convert.ToDouble(left._hertz/right._hertz); + return left.Hertz / right.Hertz; } #endif @@ -631,43 +574,43 @@ public int CompareTo(object obj) #endif int CompareTo(Frequency other) { - return _hertz.CompareTo(other._hertz); + return AsBaseUnitHertz().CompareTo(other.AsBaseUnitHertz()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Frequency left, Frequency right) { - return left._hertz <= right._hertz; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Frequency left, Frequency right) { - return left._hertz >= right._hertz; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Frequency left, Frequency right) { - return left._hertz < right._hertz; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Frequency left, Frequency right) { - return left._hertz > right._hertz; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Frequency left, Frequency right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._hertz == right._hertz; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Frequency left, Frequency right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._hertz != right._hertz; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -679,7 +622,7 @@ public override bool Equals(object obj) return false; } - return _hertz.Equals(((Frequency) obj)._hertz); + return AsBaseUnitHertz().Equals(((Frequency) obj).AsBaseUnitHertz()); } /// @@ -692,12 +635,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Frequency other, Frequency maxError) { - return Math.Abs(_hertz - other._hertz) <= maxError._hertz; + return Math.Abs(AsBaseUnitHertz() - other.AsBaseUnitHertz()) <= maxError.AsBaseUnitHertz(); } public override int GetHashCode() { - return _hertz.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -707,28 +650,26 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(FrequencyUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitHertz(); + switch (unit) { - case FrequencyUnit.CyclePerHour: - return CyclesPerHour; - case FrequencyUnit.CyclePerMinute: - return CyclesPerMinute; - case FrequencyUnit.Gigahertz: - return Gigahertz; - case FrequencyUnit.Hertz: - return Hertz; - case FrequencyUnit.Kilohertz: - return Kilohertz; - case FrequencyUnit.Megahertz: - return Megahertz; - case FrequencyUnit.RadianPerSecond: - return RadiansPerSecond; - case FrequencyUnit.Terahertz: - return Terahertz; + case FrequencyUnit.CyclePerHour: return baseUnitValue*3600; + case FrequencyUnit.CyclePerMinute: return baseUnitValue*60; + case FrequencyUnit.Gigahertz: return (baseUnitValue) / 1e9d; + case FrequencyUnit.Hertz: return baseUnitValue; + case FrequencyUnit.Kilohertz: return (baseUnitValue) / 1e3d; + case FrequencyUnit.Megahertz: return (baseUnitValue) / 1e6d; + case FrequencyUnit.RadianPerSecond: return baseUnitValue*6.2831853072; + case FrequencyUnit.Terahertz: return (baseUnitValue) / 1e12d; default: throw new NotImplementedException("unit: " + unit); @@ -770,7 +711,11 @@ public static Frequency Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -789,17 +734,24 @@ public static Frequency Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Frequency Parse(string str, [CanBeNull] Culture culture) + public static Frequency Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -825,16 +777,41 @@ public static bool TryParse([CanBeNull] string str, out Frequency result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Frequency result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Frequency result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -847,6 +824,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -860,11 +838,14 @@ public static FrequencyUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static FrequencyUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -873,6 +854,8 @@ public static FrequencyUnit ParseUnit(string str, [CanBeNull] string cultureName /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -885,18 +868,18 @@ public static FrequencyUnit ParseUnit(string str, [CanBeNull] string cultureName #else public #endif - static FrequencyUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static FrequencyUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == FrequencyUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized FrequencyUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -905,6 +888,7 @@ static FrequencyUnit ParseUnit(string str, IFormatProvider formatProvider = null #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Hertz /// @@ -916,7 +900,7 @@ static FrequencyUnit ParseUnit(string str, IFormatProvider formatProvider = null /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -933,74 +917,136 @@ public string ToString(FrequencyUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(FrequencyUnit unit, [CanBeNull] Culture culture) + public string ToString( + FrequencyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(FrequencyUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + FrequencyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(FrequencyUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + FrequencyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Frequency /// - public static Frequency MaxValue - { - get - { - return new Frequency(double.MaxValue); - } - } + public static Frequency MaxValue => new Frequency(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Frequency /// - public static Frequency MinValue + public static Frequency MinValue => new Frequency(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitHertz() { - get + if (Unit == FrequencyUnit.Hertz) { return _value; } + + switch (Unit) { - return new Frequency(double.MinValue); - } - } - } + case FrequencyUnit.CyclePerHour: return _value/3600; + case FrequencyUnit.CyclePerMinute: return _value/60; + case FrequencyUnit.Gigahertz: return (_value) * 1e9d; + case FrequencyUnit.Hertz: return _value; + case FrequencyUnit.Kilohertz: return (_value) * 1e3d; + case FrequencyUnit.Megahertz: return (_value) * 1e6d; + case FrequencyUnit.RadianPerSecond: return _value/6.2831853072; + case FrequencyUnit.Terahertz: return (_value) * 1e12d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(FrequencyUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs index 07ee8cfe60..7e3575d77c 100644 --- a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Illuminance : IComparable, IComparable #endif { /// - /// Base unit of Illuminance. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _lux; + private readonly IlluminanceUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Illuminance() : this(0) + public Illuminance() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Illuminance(double lux) { - _lux = Convert.ToDouble(lux); + _value = Convert.ToDouble(lux); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Illuminance(double numericValue, IlluminanceUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Lux. + /// + /// Value assuming base unit Lux. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Illuminance(long lux) - { - _lux = Convert.ToDouble(lux); - } + Illuminance(long lux) : this(Convert.ToDouble(lux), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Lux. + /// + /// Value assuming base unit Lux. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Illuminance(decimal lux) - { - _lux = Convert.ToDouble(lux); - } + Illuminance(decimal lux) : this(Convert.ToDouble(lux), BaseUnit) { } #region Properties @@ -119,56 +156,34 @@ public Illuminance(double lux) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static IlluminanceUnit BaseUnit - { - get { return IlluminanceUnit.Lux; } - } + public static IlluminanceUnit BaseUnit => IlluminanceUnit.Lux; /// /// All units of measurement for the Illuminance quantity. /// public static IlluminanceUnit[] Units { get; } = Enum.GetValues(typeof(IlluminanceUnit)).Cast().ToArray(); - /// /// Get Illuminance in Kilolux. /// - public double Kilolux - { - get { return (_lux) / 1e3d; } - } - + public double Kilolux => As(IlluminanceUnit.Kilolux); /// /// Get Illuminance in Lux. /// - public double Lux - { - get { return _lux; } - } - + public double Lux => As(IlluminanceUnit.Lux); /// /// Get Illuminance in Megalux. /// - public double Megalux - { - get { return (_lux) / 1e6d; } - } - + public double Megalux => As(IlluminanceUnit.Megalux); /// /// Get Illuminance in Millilux. /// - public double Millilux - { - get { return (_lux) / 1e-3d; } - } + public double Millilux => As(IlluminanceUnit.Millilux); #endregion #region Static - public static Illuminance Zero - { - get { return new Illuminance(); } - } + public static Illuminance Zero => new Illuminance(0, BaseUnit); /// /// Get Illuminance from Kilolux. @@ -176,17 +191,13 @@ public static Illuminance Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Illuminance FromKilolux(double kilolux) - { - double value = (double) kilolux; - return new Illuminance((value) * 1e3d); - } #else public static Illuminance FromKilolux(QuantityValue kilolux) +#endif { double value = (double) kilolux; - return new Illuminance(((value) * 1e3d)); + return new Illuminance(value, IlluminanceUnit.Kilolux); } -#endif /// /// Get Illuminance from Lux. @@ -194,17 +205,13 @@ public static Illuminance FromKilolux(QuantityValue kilolux) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Illuminance FromLux(double lux) - { - double value = (double) lux; - return new Illuminance(value); - } #else public static Illuminance FromLux(QuantityValue lux) +#endif { double value = (double) lux; - return new Illuminance((value)); + return new Illuminance(value, IlluminanceUnit.Lux); } -#endif /// /// Get Illuminance from Megalux. @@ -212,17 +219,13 @@ public static Illuminance FromLux(QuantityValue lux) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Illuminance FromMegalux(double megalux) - { - double value = (double) megalux; - return new Illuminance((value) * 1e6d); - } #else public static Illuminance FromMegalux(QuantityValue megalux) +#endif { double value = (double) megalux; - return new Illuminance(((value) * 1e6d)); + return new Illuminance(value, IlluminanceUnit.Megalux); } -#endif /// /// Get Illuminance from Millilux. @@ -230,17 +233,13 @@ public static Illuminance FromMegalux(QuantityValue megalux) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Illuminance FromMillilux(double millilux) - { - double value = (double) millilux; - return new Illuminance((value) * 1e-3d); - } #else public static Illuminance FromMillilux(QuantityValue millilux) +#endif { double value = (double) millilux; - return new Illuminance(((value) * 1e-3d)); + return new Illuminance(value, IlluminanceUnit.Millilux); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -320,20 +319,7 @@ public static Illuminance From(double value, IlluminanceUnit fromUnit) public static Illuminance From(QuantityValue value, IlluminanceUnit fromUnit) #endif { - switch (fromUnit) - { - case IlluminanceUnit.Kilolux: - return FromKilolux(value); - case IlluminanceUnit.Lux: - return FromLux(value); - case IlluminanceUnit.Megalux: - return FromMegalux(value); - case IlluminanceUnit.Millilux: - return FromMillilux(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Illuminance((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -350,20 +336,8 @@ public static Illuminance From(QuantityValue value, IlluminanceUnit fromUnit) { return null; } - switch (fromUnit) - { - case IlluminanceUnit.Kilolux: - return FromKilolux(value.Value); - case IlluminanceUnit.Lux: - return FromLux(value.Value); - case IlluminanceUnit.Megalux: - return FromMegalux(value.Value); - case IlluminanceUnit.Millilux: - return FromMillilux(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Illuminance((double)value.Value, fromUnit); } #endif @@ -382,12 +356,29 @@ public static string GetAbbreviation(IlluminanceUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(IlluminanceUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + IlluminanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -398,37 +389,37 @@ public static string GetAbbreviation(IlluminanceUnit unit, [CanBeNull] Culture c #if !WINDOWS_UWP public static Illuminance operator -(Illuminance right) { - return new Illuminance(-right._lux); + return new Illuminance(-right.Value, right.Unit); } public static Illuminance operator +(Illuminance left, Illuminance right) { - return new Illuminance(left._lux + right._lux); + return new Illuminance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Illuminance operator -(Illuminance left, Illuminance right) { - return new Illuminance(left._lux - right._lux); + return new Illuminance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Illuminance operator *(double left, Illuminance right) { - return new Illuminance(left*right._lux); + return new Illuminance(left * right.Value, right.Unit); } public static Illuminance operator *(Illuminance left, double right) { - return new Illuminance(left._lux*(double)right); + return new Illuminance(left.Value * right, left.Unit); } public static Illuminance operator /(Illuminance left, double right) { - return new Illuminance(left._lux/(double)right); + return new Illuminance(left.Value / right, left.Unit); } public static double operator /(Illuminance left, Illuminance right) { - return Convert.ToDouble(left._lux/right._lux); + return left.Lux / right.Lux; } #endif @@ -451,43 +442,43 @@ public int CompareTo(object obj) #endif int CompareTo(Illuminance other) { - return _lux.CompareTo(other._lux); + return AsBaseUnitLux().CompareTo(other.AsBaseUnitLux()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Illuminance left, Illuminance right) { - return left._lux <= right._lux; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Illuminance left, Illuminance right) { - return left._lux >= right._lux; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Illuminance left, Illuminance right) { - return left._lux < right._lux; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Illuminance left, Illuminance right) { - return left._lux > right._lux; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Illuminance left, Illuminance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._lux == right._lux; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Illuminance left, Illuminance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._lux != right._lux; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -499,7 +490,7 @@ public override bool Equals(object obj) return false; } - return _lux.Equals(((Illuminance) obj)._lux); + return AsBaseUnitLux().Equals(((Illuminance) obj).AsBaseUnitLux()); } /// @@ -512,12 +503,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Illuminance other, Illuminance maxError) { - return Math.Abs(_lux - other._lux) <= maxError._lux; + return Math.Abs(AsBaseUnitLux() - other.AsBaseUnitLux()) <= maxError.AsBaseUnitLux(); } public override int GetHashCode() { - return _lux.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -527,20 +518,22 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(IlluminanceUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitLux(); + switch (unit) { - case IlluminanceUnit.Kilolux: - return Kilolux; - case IlluminanceUnit.Lux: - return Lux; - case IlluminanceUnit.Megalux: - return Megalux; - case IlluminanceUnit.Millilux: - return Millilux; + case IlluminanceUnit.Kilolux: return (baseUnitValue) / 1e3d; + case IlluminanceUnit.Lux: return baseUnitValue; + case IlluminanceUnit.Megalux: return (baseUnitValue) / 1e6d; + case IlluminanceUnit.Millilux: return (baseUnitValue) / 1e-3d; default: throw new NotImplementedException("unit: " + unit); @@ -582,7 +575,11 @@ public static Illuminance Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -601,17 +598,24 @@ public static Illuminance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Illuminance Parse(string str, [CanBeNull] Culture culture) + public static Illuminance Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -637,16 +641,41 @@ public static bool TryParse([CanBeNull] string str, out Illuminance result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Illuminance result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Illuminance result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -659,6 +688,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -672,11 +702,14 @@ public static IlluminanceUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static IlluminanceUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -685,6 +718,8 @@ public static IlluminanceUnit ParseUnit(string str, [CanBeNull] string cultureNa /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -697,18 +732,18 @@ public static IlluminanceUnit ParseUnit(string str, [CanBeNull] string cultureNa #else public #endif - static IlluminanceUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static IlluminanceUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == IlluminanceUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IlluminanceUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -717,6 +752,7 @@ static IlluminanceUnit ParseUnit(string str, IFormatProvider formatProvider = nu #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Lux /// @@ -728,7 +764,7 @@ static IlluminanceUnit ParseUnit(string str, IFormatProvider formatProvider = nu /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -745,74 +781,132 @@ public string ToString(IlluminanceUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(IlluminanceUnit unit, [CanBeNull] Culture culture) + public string ToString( + IlluminanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(IlluminanceUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + IlluminanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(IlluminanceUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + IlluminanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Illuminance /// - public static Illuminance MaxValue - { - get - { - return new Illuminance(double.MaxValue); - } - } + public static Illuminance MaxValue => new Illuminance(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Illuminance /// - public static Illuminance MinValue + public static Illuminance MinValue => new Illuminance(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitLux() { - get + if (Unit == IlluminanceUnit.Lux) { return _value; } + + switch (Unit) { - return new Illuminance(double.MinValue); - } - } - } + case IlluminanceUnit.Kilolux: return (_value) * 1e3d; + case IlluminanceUnit.Lux: return _value; + case IlluminanceUnit.Megalux: return (_value) * 1e6d; + case IlluminanceUnit.Millilux: return (_value) * 1e-3d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(IlluminanceUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Information.g.cs b/UnitsNet/GeneratedCode/Quantities/Information.g.cs index ab9f0e0d79..b74ac53587 100644 --- a/UnitsNet/GeneratedCode/Quantities/Information.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Information.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Information : IComparable, IComparable #endif { /// - /// Base unit of Information. + /// The numeric value this quantity was constructed with. + /// + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly decimal _bits; + private readonly InformationUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public decimal Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Information() : this(0) + public Information() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Information(double bits) { - _bits = Convert.ToDecimal(bits); + _value = Convert.ToDecimal(bits); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Information(decimal numericValue, InformationUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Bit. + /// + /// Value assuming base unit Bit. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Information(long bits) - { - _bits = Convert.ToDecimal(bits); - } + Information(long bits) : this(Convert.ToDecimal(bits), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Bit. + /// + /// Value assuming base unit Bit. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Information(decimal bits) - { - _bits = Convert.ToDecimal(bits); - } + Information(decimal bits) : this(Convert.ToDecimal(bits), BaseUnit) { } #region Properties @@ -119,232 +156,122 @@ public Information(double bits) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static InformationUnit BaseUnit - { - get { return InformationUnit.Bit; } - } + public static InformationUnit BaseUnit => InformationUnit.Bit; /// /// All units of measurement for the Information quantity. /// public static InformationUnit[] Units { get; } = Enum.GetValues(typeof(InformationUnit)).Cast().ToArray(); - /// /// Get Information in Bits. /// - public double Bits - { - get { return Convert.ToDouble(_bits); } - } - + public double Bits => As(InformationUnit.Bit); /// /// Get Information in Bytes. /// - public double Bytes - { - get { return Convert.ToDouble(_bits/8m); } - } - + public double Bytes => As(InformationUnit.Byte); /// /// Get Information in Exabits. /// - public double Exabits - { - get { return Convert.ToDouble((_bits) / 1e18m); } - } - + public double Exabits => As(InformationUnit.Exabit); /// /// Get Information in Exabytes. /// - public double Exabytes - { - get { return Convert.ToDouble((_bits/8m) / 1e18m); } - } - + public double Exabytes => As(InformationUnit.Exabyte); /// /// Get Information in Exbibits. /// - public double Exbibits - { - get { return Convert.ToDouble((_bits) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); } - } - + public double Exbibits => As(InformationUnit.Exbibit); /// /// Get Information in Exbibytes. /// - public double Exbibytes - { - get { return Convert.ToDouble((_bits/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); } - } - + public double Exbibytes => As(InformationUnit.Exbibyte); /// /// Get Information in Gibibits. /// - public double Gibibits - { - get { return Convert.ToDouble((_bits) / (1024m * 1024 * 1024)); } - } - + public double Gibibits => As(InformationUnit.Gibibit); /// /// Get Information in Gibibytes. /// - public double Gibibytes - { - get { return Convert.ToDouble((_bits/8m) / (1024m * 1024 * 1024)); } - } - + public double Gibibytes => As(InformationUnit.Gibibyte); /// /// Get Information in Gigabits. /// - public double Gigabits - { - get { return Convert.ToDouble((_bits) / 1e9m); } - } - + public double Gigabits => As(InformationUnit.Gigabit); /// /// Get Information in Gigabytes. /// - public double Gigabytes - { - get { return Convert.ToDouble((_bits/8m) / 1e9m); } - } - + public double Gigabytes => As(InformationUnit.Gigabyte); /// /// Get Information in Kibibits. /// - public double Kibibits - { - get { return Convert.ToDouble((_bits) / 1024m); } - } - + public double Kibibits => As(InformationUnit.Kibibit); /// /// Get Information in Kibibytes. /// - public double Kibibytes - { - get { return Convert.ToDouble((_bits/8m) / 1024m); } - } - + public double Kibibytes => As(InformationUnit.Kibibyte); /// /// Get Information in Kilobits. /// - public double Kilobits - { - get { return Convert.ToDouble((_bits) / 1e3m); } - } - + public double Kilobits => As(InformationUnit.Kilobit); /// /// Get Information in Kilobytes. /// - public double Kilobytes - { - get { return Convert.ToDouble((_bits/8m) / 1e3m); } - } - + public double Kilobytes => As(InformationUnit.Kilobyte); /// /// Get Information in Mebibits. /// - public double Mebibits - { - get { return Convert.ToDouble((_bits) / (1024m * 1024)); } - } - + public double Mebibits => As(InformationUnit.Mebibit); /// /// Get Information in Mebibytes. /// - public double Mebibytes - { - get { return Convert.ToDouble((_bits/8m) / (1024m * 1024)); } - } - + public double Mebibytes => As(InformationUnit.Mebibyte); /// /// Get Information in Megabits. /// - public double Megabits - { - get { return Convert.ToDouble((_bits) / 1e6m); } - } - + public double Megabits => As(InformationUnit.Megabit); /// /// Get Information in Megabytes. /// - public double Megabytes - { - get { return Convert.ToDouble((_bits/8m) / 1e6m); } - } - + public double Megabytes => As(InformationUnit.Megabyte); /// /// Get Information in Pebibits. /// - public double Pebibits - { - get { return Convert.ToDouble((_bits) / (1024m * 1024 * 1024 * 1024 * 1024)); } - } - + public double Pebibits => As(InformationUnit.Pebibit); /// /// Get Information in Pebibytes. /// - public double Pebibytes - { - get { return Convert.ToDouble((_bits/8m) / (1024m * 1024 * 1024 * 1024 * 1024)); } - } - + public double Pebibytes => As(InformationUnit.Pebibyte); /// /// Get Information in Petabits. /// - public double Petabits - { - get { return Convert.ToDouble((_bits) / 1e15m); } - } - + public double Petabits => As(InformationUnit.Petabit); /// /// Get Information in Petabytes. /// - public double Petabytes - { - get { return Convert.ToDouble((_bits/8m) / 1e15m); } - } - + public double Petabytes => As(InformationUnit.Petabyte); /// /// Get Information in Tebibits. /// - public double Tebibits - { - get { return Convert.ToDouble((_bits) / (1024m * 1024 * 1024 * 1024)); } - } - + public double Tebibits => As(InformationUnit.Tebibit); /// /// Get Information in Tebibytes. /// - public double Tebibytes - { - get { return Convert.ToDouble((_bits/8m) / (1024m * 1024 * 1024 * 1024)); } - } - + public double Tebibytes => As(InformationUnit.Tebibyte); /// /// Get Information in Terabits. /// - public double Terabits - { - get { return Convert.ToDouble((_bits) / 1e12m); } - } - + public double Terabits => As(InformationUnit.Terabit); /// /// Get Information in Terabytes. /// - public double Terabytes - { - get { return Convert.ToDouble((_bits/8m) / 1e12m); } - } + public double Terabytes => As(InformationUnit.Terabyte); #endregion #region Static - public static Information Zero - { - get { return new Information(); } - } + public static Information Zero => new Information(0, BaseUnit); /// /// Get Information from Bits. @@ -352,17 +279,13 @@ public static Information Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromBits(double bits) - { - double value = (double) bits; - return new Information(Convert.ToDecimal(value)); - } #else public static Information FromBits(QuantityValue bits) +#endif { - double value = (double) bits; - return new Information((Convert.ToDecimal(value))); + decimal value = (decimal) bits; + return new Information(value, InformationUnit.Bit); } -#endif /// /// Get Information from Bytes. @@ -370,17 +293,13 @@ public static Information FromBits(QuantityValue bits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromBytes(double bytes) - { - double value = (double) bytes; - return new Information(Convert.ToDecimal(value*8d)); - } #else public static Information FromBytes(QuantityValue bytes) +#endif { - double value = (double) bytes; - return new Information((Convert.ToDecimal(value*8d))); + decimal value = (decimal) bytes; + return new Information(value, InformationUnit.Byte); } -#endif /// /// Get Information from Exabits. @@ -388,17 +307,13 @@ public static Information FromBytes(QuantityValue bytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromExabits(double exabits) - { - double value = (double) exabits; - return new Information(Convert.ToDecimal((value) * 1e18d)); - } #else public static Information FromExabits(QuantityValue exabits) +#endif { - double value = (double) exabits; - return new Information((Convert.ToDecimal((value) * 1e18d))); + decimal value = (decimal) exabits; + return new Information(value, InformationUnit.Exabit); } -#endif /// /// Get Information from Exabytes. @@ -406,17 +321,13 @@ public static Information FromExabits(QuantityValue exabits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromExabytes(double exabytes) - { - double value = (double) exabytes; - return new Information(Convert.ToDecimal((value*8d) * 1e18d)); - } #else public static Information FromExabytes(QuantityValue exabytes) +#endif { - double value = (double) exabytes; - return new Information((Convert.ToDecimal((value*8d) * 1e18d))); + decimal value = (decimal) exabytes; + return new Information(value, InformationUnit.Exabyte); } -#endif /// /// Get Information from Exbibits. @@ -424,17 +335,13 @@ public static Information FromExabytes(QuantityValue exabytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromExbibits(double exbibits) - { - double value = (double) exbibits; - return new Information(Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024))); - } #else public static Information FromExbibits(QuantityValue exbibits) +#endif { - double value = (double) exbibits; - return new Information((Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024)))); + decimal value = (decimal) exbibits; + return new Information(value, InformationUnit.Exbibit); } -#endif /// /// Get Information from Exbibytes. @@ -442,17 +349,13 @@ public static Information FromExbibits(QuantityValue exbibits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromExbibytes(double exbibytes) - { - double value = (double) exbibytes; - return new Information(Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024))); - } #else public static Information FromExbibytes(QuantityValue exbibytes) +#endif { - double value = (double) exbibytes; - return new Information((Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024)))); + decimal value = (decimal) exbibytes; + return new Information(value, InformationUnit.Exbibyte); } -#endif /// /// Get Information from Gibibits. @@ -460,17 +363,13 @@ public static Information FromExbibytes(QuantityValue exbibytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromGibibits(double gibibits) - { - double value = (double) gibibits; - return new Information(Convert.ToDecimal((value) * (1024d * 1024 * 1024))); - } #else public static Information FromGibibits(QuantityValue gibibits) +#endif { - double value = (double) gibibits; - return new Information((Convert.ToDecimal((value) * (1024d * 1024 * 1024)))); + decimal value = (decimal) gibibits; + return new Information(value, InformationUnit.Gibibit); } -#endif /// /// Get Information from Gibibytes. @@ -478,17 +377,13 @@ public static Information FromGibibits(QuantityValue gibibits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromGibibytes(double gibibytes) - { - double value = (double) gibibytes; - return new Information(Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024))); - } #else public static Information FromGibibytes(QuantityValue gibibytes) +#endif { - double value = (double) gibibytes; - return new Information((Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024)))); + decimal value = (decimal) gibibytes; + return new Information(value, InformationUnit.Gibibyte); } -#endif /// /// Get Information from Gigabits. @@ -496,17 +391,13 @@ public static Information FromGibibytes(QuantityValue gibibytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromGigabits(double gigabits) - { - double value = (double) gigabits; - return new Information(Convert.ToDecimal((value) * 1e9d)); - } #else public static Information FromGigabits(QuantityValue gigabits) +#endif { - double value = (double) gigabits; - return new Information((Convert.ToDecimal((value) * 1e9d))); + decimal value = (decimal) gigabits; + return new Information(value, InformationUnit.Gigabit); } -#endif /// /// Get Information from Gigabytes. @@ -514,17 +405,13 @@ public static Information FromGigabits(QuantityValue gigabits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromGigabytes(double gigabytes) - { - double value = (double) gigabytes; - return new Information(Convert.ToDecimal((value*8d) * 1e9d)); - } #else public static Information FromGigabytes(QuantityValue gigabytes) +#endif { - double value = (double) gigabytes; - return new Information((Convert.ToDecimal((value*8d) * 1e9d))); + decimal value = (decimal) gigabytes; + return new Information(value, InformationUnit.Gigabyte); } -#endif /// /// Get Information from Kibibits. @@ -532,17 +419,13 @@ public static Information FromGigabytes(QuantityValue gigabytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromKibibits(double kibibits) - { - double value = (double) kibibits; - return new Information(Convert.ToDecimal((value) * 1024d)); - } #else public static Information FromKibibits(QuantityValue kibibits) +#endif { - double value = (double) kibibits; - return new Information((Convert.ToDecimal((value) * 1024d))); + decimal value = (decimal) kibibits; + return new Information(value, InformationUnit.Kibibit); } -#endif /// /// Get Information from Kibibytes. @@ -550,17 +433,13 @@ public static Information FromKibibits(QuantityValue kibibits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromKibibytes(double kibibytes) - { - double value = (double) kibibytes; - return new Information(Convert.ToDecimal((value*8d) * 1024d)); - } #else public static Information FromKibibytes(QuantityValue kibibytes) +#endif { - double value = (double) kibibytes; - return new Information((Convert.ToDecimal((value*8d) * 1024d))); + decimal value = (decimal) kibibytes; + return new Information(value, InformationUnit.Kibibyte); } -#endif /// /// Get Information from Kilobits. @@ -568,17 +447,13 @@ public static Information FromKibibytes(QuantityValue kibibytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromKilobits(double kilobits) - { - double value = (double) kilobits; - return new Information(Convert.ToDecimal((value) * 1e3d)); - } #else public static Information FromKilobits(QuantityValue kilobits) +#endif { - double value = (double) kilobits; - return new Information((Convert.ToDecimal((value) * 1e3d))); + decimal value = (decimal) kilobits; + return new Information(value, InformationUnit.Kilobit); } -#endif /// /// Get Information from Kilobytes. @@ -586,17 +461,13 @@ public static Information FromKilobits(QuantityValue kilobits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromKilobytes(double kilobytes) - { - double value = (double) kilobytes; - return new Information(Convert.ToDecimal((value*8d) * 1e3d)); - } #else public static Information FromKilobytes(QuantityValue kilobytes) +#endif { - double value = (double) kilobytes; - return new Information((Convert.ToDecimal((value*8d) * 1e3d))); + decimal value = (decimal) kilobytes; + return new Information(value, InformationUnit.Kilobyte); } -#endif /// /// Get Information from Mebibits. @@ -604,17 +475,13 @@ public static Information FromKilobytes(QuantityValue kilobytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromMebibits(double mebibits) - { - double value = (double) mebibits; - return new Information(Convert.ToDecimal((value) * (1024d * 1024))); - } #else public static Information FromMebibits(QuantityValue mebibits) +#endif { - double value = (double) mebibits; - return new Information((Convert.ToDecimal((value) * (1024d * 1024)))); + decimal value = (decimal) mebibits; + return new Information(value, InformationUnit.Mebibit); } -#endif /// /// Get Information from Mebibytes. @@ -622,17 +489,13 @@ public static Information FromMebibits(QuantityValue mebibits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromMebibytes(double mebibytes) - { - double value = (double) mebibytes; - return new Information(Convert.ToDecimal((value*8d) * (1024d * 1024))); - } #else public static Information FromMebibytes(QuantityValue mebibytes) +#endif { - double value = (double) mebibytes; - return new Information((Convert.ToDecimal((value*8d) * (1024d * 1024)))); + decimal value = (decimal) mebibytes; + return new Information(value, InformationUnit.Mebibyte); } -#endif /// /// Get Information from Megabits. @@ -640,17 +503,13 @@ public static Information FromMebibytes(QuantityValue mebibytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromMegabits(double megabits) - { - double value = (double) megabits; - return new Information(Convert.ToDecimal((value) * 1e6d)); - } #else public static Information FromMegabits(QuantityValue megabits) +#endif { - double value = (double) megabits; - return new Information((Convert.ToDecimal((value) * 1e6d))); + decimal value = (decimal) megabits; + return new Information(value, InformationUnit.Megabit); } -#endif /// /// Get Information from Megabytes. @@ -658,17 +517,13 @@ public static Information FromMegabits(QuantityValue megabits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromMegabytes(double megabytes) - { - double value = (double) megabytes; - return new Information(Convert.ToDecimal((value*8d) * 1e6d)); - } #else public static Information FromMegabytes(QuantityValue megabytes) +#endif { - double value = (double) megabytes; - return new Information((Convert.ToDecimal((value*8d) * 1e6d))); + decimal value = (decimal) megabytes; + return new Information(value, InformationUnit.Megabyte); } -#endif /// /// Get Information from Pebibits. @@ -676,17 +531,13 @@ public static Information FromMegabytes(QuantityValue megabytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromPebibits(double pebibits) - { - double value = (double) pebibits; - return new Information(Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024 * 1024))); - } #else public static Information FromPebibits(QuantityValue pebibits) +#endif { - double value = (double) pebibits; - return new Information((Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024 * 1024)))); + decimal value = (decimal) pebibits; + return new Information(value, InformationUnit.Pebibit); } -#endif /// /// Get Information from Pebibytes. @@ -694,17 +545,13 @@ public static Information FromPebibits(QuantityValue pebibits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromPebibytes(double pebibytes) - { - double value = (double) pebibytes; - return new Information(Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024 * 1024))); - } #else public static Information FromPebibytes(QuantityValue pebibytes) +#endif { - double value = (double) pebibytes; - return new Information((Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024 * 1024)))); + decimal value = (decimal) pebibytes; + return new Information(value, InformationUnit.Pebibyte); } -#endif /// /// Get Information from Petabits. @@ -712,17 +559,13 @@ public static Information FromPebibytes(QuantityValue pebibytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromPetabits(double petabits) - { - double value = (double) petabits; - return new Information(Convert.ToDecimal((value) * 1e15d)); - } #else public static Information FromPetabits(QuantityValue petabits) +#endif { - double value = (double) petabits; - return new Information((Convert.ToDecimal((value) * 1e15d))); + decimal value = (decimal) petabits; + return new Information(value, InformationUnit.Petabit); } -#endif /// /// Get Information from Petabytes. @@ -730,17 +573,13 @@ public static Information FromPetabits(QuantityValue petabits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromPetabytes(double petabytes) - { - double value = (double) petabytes; - return new Information(Convert.ToDecimal((value*8d) * 1e15d)); - } #else public static Information FromPetabytes(QuantityValue petabytes) +#endif { - double value = (double) petabytes; - return new Information((Convert.ToDecimal((value*8d) * 1e15d))); + decimal value = (decimal) petabytes; + return new Information(value, InformationUnit.Petabyte); } -#endif /// /// Get Information from Tebibits. @@ -748,17 +587,13 @@ public static Information FromPetabytes(QuantityValue petabytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromTebibits(double tebibits) - { - double value = (double) tebibits; - return new Information(Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024))); - } #else public static Information FromTebibits(QuantityValue tebibits) +#endif { - double value = (double) tebibits; - return new Information((Convert.ToDecimal((value) * (1024d * 1024 * 1024 * 1024)))); + decimal value = (decimal) tebibits; + return new Information(value, InformationUnit.Tebibit); } -#endif /// /// Get Information from Tebibytes. @@ -766,17 +601,13 @@ public static Information FromTebibits(QuantityValue tebibits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromTebibytes(double tebibytes) - { - double value = (double) tebibytes; - return new Information(Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024))); - } #else public static Information FromTebibytes(QuantityValue tebibytes) +#endif { - double value = (double) tebibytes; - return new Information((Convert.ToDecimal((value*8d) * (1024d * 1024 * 1024 * 1024)))); + decimal value = (decimal) tebibytes; + return new Information(value, InformationUnit.Tebibyte); } -#endif /// /// Get Information from Terabits. @@ -784,17 +615,13 @@ public static Information FromTebibytes(QuantityValue tebibytes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromTerabits(double terabits) - { - double value = (double) terabits; - return new Information(Convert.ToDecimal((value) * 1e12d)); - } #else public static Information FromTerabits(QuantityValue terabits) +#endif { - double value = (double) terabits; - return new Information((Convert.ToDecimal((value) * 1e12d))); + decimal value = (decimal) terabits; + return new Information(value, InformationUnit.Terabit); } -#endif /// /// Get Information from Terabytes. @@ -802,17 +629,13 @@ public static Information FromTerabits(QuantityValue terabits) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Information FromTerabytes(double terabytes) - { - double value = (double) terabytes; - return new Information(Convert.ToDecimal((value*8d) * 1e12d)); - } #else public static Information FromTerabytes(QuantityValue terabytes) +#endif { - double value = (double) terabytes; - return new Information((Convert.ToDecimal((value*8d) * 1e12d))); + decimal value = (decimal) terabytes; + return new Information(value, InformationUnit.Terabyte); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1222,64 +1045,7 @@ public static Information From(double value, InformationUnit fromUnit) public static Information From(QuantityValue value, InformationUnit fromUnit) #endif { - switch (fromUnit) - { - case InformationUnit.Bit: - return FromBits(value); - case InformationUnit.Byte: - return FromBytes(value); - case InformationUnit.Exabit: - return FromExabits(value); - case InformationUnit.Exabyte: - return FromExabytes(value); - case InformationUnit.Exbibit: - return FromExbibits(value); - case InformationUnit.Exbibyte: - return FromExbibytes(value); - case InformationUnit.Gibibit: - return FromGibibits(value); - case InformationUnit.Gibibyte: - return FromGibibytes(value); - case InformationUnit.Gigabit: - return FromGigabits(value); - case InformationUnit.Gigabyte: - return FromGigabytes(value); - case InformationUnit.Kibibit: - return FromKibibits(value); - case InformationUnit.Kibibyte: - return FromKibibytes(value); - case InformationUnit.Kilobit: - return FromKilobits(value); - case InformationUnit.Kilobyte: - return FromKilobytes(value); - case InformationUnit.Mebibit: - return FromMebibits(value); - case InformationUnit.Mebibyte: - return FromMebibytes(value); - case InformationUnit.Megabit: - return FromMegabits(value); - case InformationUnit.Megabyte: - return FromMegabytes(value); - case InformationUnit.Pebibit: - return FromPebibits(value); - case InformationUnit.Pebibyte: - return FromPebibytes(value); - case InformationUnit.Petabit: - return FromPetabits(value); - case InformationUnit.Petabyte: - return FromPetabytes(value); - case InformationUnit.Tebibit: - return FromTebibits(value); - case InformationUnit.Tebibyte: - return FromTebibytes(value); - case InformationUnit.Terabit: - return FromTerabits(value); - case InformationUnit.Terabyte: - return FromTerabytes(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Information((decimal)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1296,64 +1062,8 @@ public static Information From(QuantityValue value, InformationUnit fromUnit) { return null; } - switch (fromUnit) - { - case InformationUnit.Bit: - return FromBits(value.Value); - case InformationUnit.Byte: - return FromBytes(value.Value); - case InformationUnit.Exabit: - return FromExabits(value.Value); - case InformationUnit.Exabyte: - return FromExabytes(value.Value); - case InformationUnit.Exbibit: - return FromExbibits(value.Value); - case InformationUnit.Exbibyte: - return FromExbibytes(value.Value); - case InformationUnit.Gibibit: - return FromGibibits(value.Value); - case InformationUnit.Gibibyte: - return FromGibibytes(value.Value); - case InformationUnit.Gigabit: - return FromGigabits(value.Value); - case InformationUnit.Gigabyte: - return FromGigabytes(value.Value); - case InformationUnit.Kibibit: - return FromKibibits(value.Value); - case InformationUnit.Kibibyte: - return FromKibibytes(value.Value); - case InformationUnit.Kilobit: - return FromKilobits(value.Value); - case InformationUnit.Kilobyte: - return FromKilobytes(value.Value); - case InformationUnit.Mebibit: - return FromMebibits(value.Value); - case InformationUnit.Mebibyte: - return FromMebibytes(value.Value); - case InformationUnit.Megabit: - return FromMegabits(value.Value); - case InformationUnit.Megabyte: - return FromMegabytes(value.Value); - case InformationUnit.Pebibit: - return FromPebibits(value.Value); - case InformationUnit.Pebibyte: - return FromPebibytes(value.Value); - case InformationUnit.Petabit: - return FromPetabits(value.Value); - case InformationUnit.Petabyte: - return FromPetabytes(value.Value); - case InformationUnit.Tebibit: - return FromTebibits(value.Value); - case InformationUnit.Tebibyte: - return FromTebibytes(value.Value); - case InformationUnit.Terabit: - return FromTerabits(value.Value); - case InformationUnit.Terabyte: - return FromTerabytes(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Information((decimal)value.Value, fromUnit); } #endif @@ -1372,12 +1082,29 @@ public static string GetAbbreviation(InformationUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(InformationUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + InformationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1388,37 +1115,37 @@ public static string GetAbbreviation(InformationUnit unit, [CanBeNull] Culture c #if !WINDOWS_UWP public static Information operator -(Information right) { - return new Information(-right._bits); + return new Information(-right.Value, right.Unit); } public static Information operator +(Information left, Information right) { - return new Information(left._bits + right._bits); + return new Information(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Information operator -(Information left, Information right) { - return new Information(left._bits - right._bits); + return new Information(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Information operator *(decimal left, Information right) { - return new Information(left*right._bits); + return new Information(left * right.Value, right.Unit); } - public static Information operator *(Information left, double right) + public static Information operator *(Information left, decimal right) { - return new Information(left._bits*(decimal)right); + return new Information(left.Value * right, left.Unit); } - public static Information operator /(Information left, double right) + public static Information operator /(Information left, decimal right) { - return new Information(left._bits/(decimal)right); + return new Information(left.Value / right, left.Unit); } public static double operator /(Information left, Information right) { - return Convert.ToDouble(left._bits/right._bits); + return left.Bits / right.Bits; } #endif @@ -1441,41 +1168,41 @@ public int CompareTo(object obj) #endif int CompareTo(Information other) { - return _bits.CompareTo(other._bits); + return AsBaseUnitBits().CompareTo(other.AsBaseUnitBits()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Information left, Information right) { - return left._bits <= right._bits; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Information left, Information right) { - return left._bits >= right._bits; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Information left, Information right) { - return left._bits < right._bits; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Information left, Information right) { - return left._bits > right._bits; + return left.Value > right.AsBaseNumericType(left.Unit); } public static bool operator ==(Information left, Information right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._bits == right._bits; + return left.Value == right.AsBaseNumericType(left.Unit); } public static bool operator !=(Information left, Information right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._bits != right._bits; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1486,7 +1213,7 @@ public override bool Equals(object obj) return false; } - return _bits.Equals(((Information) obj)._bits); + return AsBaseUnitBits().Equals(((Information) obj).AsBaseUnitBits()); } /// @@ -1499,12 +1226,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Information other, Information maxError) { - return Math.Abs(_bits - other._bits) <= maxError._bits; + return Math.Abs(AsBaseUnitBits() - other.AsBaseUnitBits()) <= maxError.AsBaseUnitBits(); } public override int GetHashCode() { - return _bits.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1514,64 +1241,44 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(InformationUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + decimal baseUnitValue = AsBaseUnitBits(); + switch (unit) { - case InformationUnit.Bit: - return Bits; - case InformationUnit.Byte: - return Bytes; - case InformationUnit.Exabit: - return Exabits; - case InformationUnit.Exabyte: - return Exabytes; - case InformationUnit.Exbibit: - return Exbibits; - case InformationUnit.Exbibyte: - return Exbibytes; - case InformationUnit.Gibibit: - return Gibibits; - case InformationUnit.Gibibyte: - return Gibibytes; - case InformationUnit.Gigabit: - return Gigabits; - case InformationUnit.Gigabyte: - return Gigabytes; - case InformationUnit.Kibibit: - return Kibibits; - case InformationUnit.Kibibyte: - return Kibibytes; - case InformationUnit.Kilobit: - return Kilobits; - case InformationUnit.Kilobyte: - return Kilobytes; - case InformationUnit.Mebibit: - return Mebibits; - case InformationUnit.Mebibyte: - return Mebibytes; - case InformationUnit.Megabit: - return Megabits; - case InformationUnit.Megabyte: - return Megabytes; - case InformationUnit.Pebibit: - return Pebibits; - case InformationUnit.Pebibyte: - return Pebibytes; - case InformationUnit.Petabit: - return Petabits; - case InformationUnit.Petabyte: - return Petabytes; - case InformationUnit.Tebibit: - return Tebibits; - case InformationUnit.Tebibyte: - return Tebibytes; - case InformationUnit.Terabit: - return Terabits; - case InformationUnit.Terabyte: - return Terabytes; + case InformationUnit.Bit: return Convert.ToDouble(baseUnitValue); + case InformationUnit.Byte: return Convert.ToDouble(baseUnitValue/8m); + case InformationUnit.Exabit: return Convert.ToDouble((baseUnitValue) / 1e18m); + case InformationUnit.Exabyte: return Convert.ToDouble((baseUnitValue/8m) / 1e18m); + case InformationUnit.Exbibit: return Convert.ToDouble((baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); + case InformationUnit.Exbibyte: return Convert.ToDouble((baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); + case InformationUnit.Gibibit: return Convert.ToDouble((baseUnitValue) / (1024m * 1024 * 1024)); + case InformationUnit.Gibibyte: return Convert.ToDouble((baseUnitValue/8m) / (1024m * 1024 * 1024)); + case InformationUnit.Gigabit: return Convert.ToDouble((baseUnitValue) / 1e9m); + case InformationUnit.Gigabyte: return Convert.ToDouble((baseUnitValue/8m) / 1e9m); + case InformationUnit.Kibibit: return Convert.ToDouble((baseUnitValue) / 1024m); + case InformationUnit.Kibibyte: return Convert.ToDouble((baseUnitValue/8m) / 1024m); + case InformationUnit.Kilobit: return Convert.ToDouble((baseUnitValue) / 1e3m); + case InformationUnit.Kilobyte: return Convert.ToDouble((baseUnitValue/8m) / 1e3m); + case InformationUnit.Mebibit: return Convert.ToDouble((baseUnitValue) / (1024m * 1024)); + case InformationUnit.Mebibyte: return Convert.ToDouble((baseUnitValue/8m) / (1024m * 1024)); + case InformationUnit.Megabit: return Convert.ToDouble((baseUnitValue) / 1e6m); + case InformationUnit.Megabyte: return Convert.ToDouble((baseUnitValue/8m) / 1e6m); + case InformationUnit.Pebibit: return Convert.ToDouble((baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024)); + case InformationUnit.Pebibyte: return Convert.ToDouble((baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024)); + case InformationUnit.Petabit: return Convert.ToDouble((baseUnitValue) / 1e15m); + case InformationUnit.Petabyte: return Convert.ToDouble((baseUnitValue/8m) / 1e15m); + case InformationUnit.Tebibit: return Convert.ToDouble((baseUnitValue) / (1024m * 1024 * 1024 * 1024)); + case InformationUnit.Tebibyte: return Convert.ToDouble((baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024)); + case InformationUnit.Terabit: return Convert.ToDouble((baseUnitValue) / 1e12m); + case InformationUnit.Terabyte: return Convert.ToDouble((baseUnitValue/8m) / 1e12m); default: throw new NotImplementedException("unit: " + unit); @@ -1613,7 +1320,11 @@ public static Information Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1632,17 +1343,24 @@ public static Information Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Information Parse(string str, [CanBeNull] Culture culture) + public static Information Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1668,16 +1386,41 @@ public static bool TryParse([CanBeNull] string str, out Information result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Information result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Information result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1690,6 +1433,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1703,11 +1447,14 @@ public static InformationUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static InformationUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1716,6 +1463,8 @@ public static InformationUnit ParseUnit(string str, [CanBeNull] string cultureNa /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1728,18 +1477,18 @@ public static InformationUnit ParseUnit(string str, [CanBeNull] string cultureNa #else public #endif - static InformationUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static InformationUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == InformationUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized InformationUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1748,6 +1497,7 @@ static InformationUnit ParseUnit(string str, IFormatProvider formatProvider = nu #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Bit /// @@ -1759,7 +1509,7 @@ static InformationUnit ParseUnit(string str, IFormatProvider formatProvider = nu /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1776,74 +1526,154 @@ public string ToString(InformationUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(InformationUnit unit, [CanBeNull] Culture culture) + public string ToString( + InformationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(InformationUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + InformationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(InformationUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + InformationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Information /// - public static Information MaxValue - { - get - { - return new Information(decimal.MaxValue); - } - } + public static Information MaxValue => new Information(decimal.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Information /// - public static Information MinValue + public static Information MinValue => new Information(decimal.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private decimal AsBaseUnitBits() { - get + if (Unit == InformationUnit.Bit) { return _value; } + + switch (Unit) { - return new Information(decimal.MinValue); - } - } - } + case InformationUnit.Bit: return Convert.ToDecimal(_value); + case InformationUnit.Byte: return Convert.ToDecimal(_value*8m); + case InformationUnit.Exabit: return Convert.ToDecimal((_value) * 1e18m); + case InformationUnit.Exabyte: return Convert.ToDecimal((_value*8m) * 1e18m); + case InformationUnit.Exbibit: return Convert.ToDecimal((_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); + case InformationUnit.Exbibyte: return Convert.ToDecimal((_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024)); + case InformationUnit.Gibibit: return Convert.ToDecimal((_value) * (1024m * 1024 * 1024)); + case InformationUnit.Gibibyte: return Convert.ToDecimal((_value*8m) * (1024m * 1024 * 1024)); + case InformationUnit.Gigabit: return Convert.ToDecimal((_value) * 1e9m); + case InformationUnit.Gigabyte: return Convert.ToDecimal((_value*8m) * 1e9m); + case InformationUnit.Kibibit: return Convert.ToDecimal((_value) * 1024m); + case InformationUnit.Kibibyte: return Convert.ToDecimal((_value*8m) * 1024m); + case InformationUnit.Kilobit: return Convert.ToDecimal((_value) * 1e3m); + case InformationUnit.Kilobyte: return Convert.ToDecimal((_value*8m) * 1e3m); + case InformationUnit.Mebibit: return Convert.ToDecimal((_value) * (1024m * 1024)); + case InformationUnit.Mebibyte: return Convert.ToDecimal((_value*8m) * (1024m * 1024)); + case InformationUnit.Megabit: return Convert.ToDecimal((_value) * 1e6m); + case InformationUnit.Megabyte: return Convert.ToDecimal((_value*8m) * 1e6m); + case InformationUnit.Pebibit: return Convert.ToDecimal((_value) * (1024m * 1024 * 1024 * 1024 * 1024)); + case InformationUnit.Pebibyte: return Convert.ToDecimal((_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024)); + case InformationUnit.Petabit: return Convert.ToDecimal((_value) * 1e15m); + case InformationUnit.Petabyte: return Convert.ToDecimal((_value*8m) * 1e15m); + case InformationUnit.Tebibit: return Convert.ToDecimal((_value) * (1024m * 1024 * 1024 * 1024)); + case InformationUnit.Tebibyte: return Convert.ToDecimal((_value*8m) * (1024m * 1024 * 1024 * 1024)); + case InformationUnit.Terabit: return Convert.ToDecimal((_value) * 1e12m); + case InformationUnit.Terabyte: return Convert.ToDecimal((_value*8m) * 1e12m); + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private decimal AsBaseNumericType(InformationUnit unit) => Convert.ToDecimal(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs index 2567d73493..880a035dc4 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Irradiance : IComparable, IComparable #endif { /// - /// Base unit of Irradiance. + /// The numeric value this quantity was constructed with. /// - private readonly double _wattsPerSquareMeter; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly IrradianceUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Irradiance() : this(0) + public Irradiance() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Irradiance(double wattspersquaremeter) { - _wattsPerSquareMeter = Convert.ToDouble(wattspersquaremeter); + _value = Convert.ToDouble(wattspersquaremeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Irradiance(double numericValue, IrradianceUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit WattPerSquareMeter. + /// + /// Value assuming base unit WattPerSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Irradiance(long wattspersquaremeter) - { - _wattsPerSquareMeter = Convert.ToDouble(wattspersquaremeter); - } + Irradiance(long wattspersquaremeter) : this(Convert.ToDouble(wattspersquaremeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit WattPerSquareMeter. + /// + /// Value assuming base unit WattPerSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Irradiance(decimal wattspersquaremeter) - { - _wattsPerSquareMeter = Convert.ToDouble(wattspersquaremeter); - } + Irradiance(decimal wattspersquaremeter) : this(Convert.ToDouble(wattspersquaremeter), BaseUnit) { } #region Properties @@ -119,40 +156,26 @@ public Irradiance(double wattspersquaremeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static IrradianceUnit BaseUnit - { - get { return IrradianceUnit.WattPerSquareMeter; } - } + public static IrradianceUnit BaseUnit => IrradianceUnit.WattPerSquareMeter; /// /// All units of measurement for the Irradiance quantity. /// public static IrradianceUnit[] Units { get; } = Enum.GetValues(typeof(IrradianceUnit)).Cast().ToArray(); - /// /// Get Irradiance in KilowattsPerSquareMeter. /// - public double KilowattsPerSquareMeter - { - get { return (_wattsPerSquareMeter) / 1e3d; } - } - + public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); /// /// Get Irradiance in WattsPerSquareMeter. /// - public double WattsPerSquareMeter - { - get { return _wattsPerSquareMeter; } - } + public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); #endregion #region Static - public static Irradiance Zero - { - get { return new Irradiance(); } - } + public static Irradiance Zero => new Irradiance(0, BaseUnit); /// /// Get Irradiance from KilowattsPerSquareMeter. @@ -160,17 +183,13 @@ public static Irradiance Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Irradiance FromKilowattsPerSquareMeter(double kilowattspersquaremeter) - { - double value = (double) kilowattspersquaremeter; - return new Irradiance((value) * 1e3d); - } #else public static Irradiance FromKilowattsPerSquareMeter(QuantityValue kilowattspersquaremeter) +#endif { double value = (double) kilowattspersquaremeter; - return new Irradiance(((value) * 1e3d)); + return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); } -#endif /// /// Get Irradiance from WattsPerSquareMeter. @@ -178,17 +197,13 @@ public static Irradiance FromKilowattsPerSquareMeter(QuantityValue kilowattspers #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Irradiance FromWattsPerSquareMeter(double wattspersquaremeter) - { - double value = (double) wattspersquaremeter; - return new Irradiance(value); - } #else public static Irradiance FromWattsPerSquareMeter(QuantityValue wattspersquaremeter) +#endif { double value = (double) wattspersquaremeter; - return new Irradiance((value)); + return new Irradiance(value, IrradianceUnit.WattPerSquareMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -238,16 +253,7 @@ public static Irradiance From(double value, IrradianceUnit fromUnit) public static Irradiance From(QuantityValue value, IrradianceUnit fromUnit) #endif { - switch (fromUnit) - { - case IrradianceUnit.KilowattPerSquareMeter: - return FromKilowattsPerSquareMeter(value); - case IrradianceUnit.WattPerSquareMeter: - return FromWattsPerSquareMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Irradiance((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -264,16 +270,8 @@ public static Irradiance From(QuantityValue value, IrradianceUnit fromUnit) { return null; } - switch (fromUnit) - { - case IrradianceUnit.KilowattPerSquareMeter: - return FromKilowattsPerSquareMeter(value.Value); - case IrradianceUnit.WattPerSquareMeter: - return FromWattsPerSquareMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Irradiance((double)value.Value, fromUnit); } #endif @@ -292,12 +290,29 @@ public static string GetAbbreviation(IrradianceUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(IrradianceUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + IrradianceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -308,37 +323,37 @@ public static string GetAbbreviation(IrradianceUnit unit, [CanBeNull] Culture cu #if !WINDOWS_UWP public static Irradiance operator -(Irradiance right) { - return new Irradiance(-right._wattsPerSquareMeter); + return new Irradiance(-right.Value, right.Unit); } public static Irradiance operator +(Irradiance left, Irradiance right) { - return new Irradiance(left._wattsPerSquareMeter + right._wattsPerSquareMeter); + return new Irradiance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Irradiance operator -(Irradiance left, Irradiance right) { - return new Irradiance(left._wattsPerSquareMeter - right._wattsPerSquareMeter); + return new Irradiance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Irradiance operator *(double left, Irradiance right) { - return new Irradiance(left*right._wattsPerSquareMeter); + return new Irradiance(left * right.Value, right.Unit); } public static Irradiance operator *(Irradiance left, double right) { - return new Irradiance(left._wattsPerSquareMeter*(double)right); + return new Irradiance(left.Value * right, left.Unit); } public static Irradiance operator /(Irradiance left, double right) { - return new Irradiance(left._wattsPerSquareMeter/(double)right); + return new Irradiance(left.Value / right, left.Unit); } public static double operator /(Irradiance left, Irradiance right) { - return Convert.ToDouble(left._wattsPerSquareMeter/right._wattsPerSquareMeter); + return left.WattsPerSquareMeter / right.WattsPerSquareMeter; } #endif @@ -361,43 +376,43 @@ public int CompareTo(object obj) #endif int CompareTo(Irradiance other) { - return _wattsPerSquareMeter.CompareTo(other._wattsPerSquareMeter); + return AsBaseUnitWattsPerSquareMeter().CompareTo(other.AsBaseUnitWattsPerSquareMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Irradiance left, Irradiance right) { - return left._wattsPerSquareMeter <= right._wattsPerSquareMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Irradiance left, Irradiance right) { - return left._wattsPerSquareMeter >= right._wattsPerSquareMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Irradiance left, Irradiance right) { - return left._wattsPerSquareMeter < right._wattsPerSquareMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Irradiance left, Irradiance right) { - return left._wattsPerSquareMeter > right._wattsPerSquareMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Irradiance left, Irradiance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._wattsPerSquareMeter == right._wattsPerSquareMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Irradiance left, Irradiance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._wattsPerSquareMeter != right._wattsPerSquareMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -409,7 +424,7 @@ public override bool Equals(object obj) return false; } - return _wattsPerSquareMeter.Equals(((Irradiance) obj)._wattsPerSquareMeter); + return AsBaseUnitWattsPerSquareMeter().Equals(((Irradiance) obj).AsBaseUnitWattsPerSquareMeter()); } /// @@ -422,12 +437,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Irradiance other, Irradiance maxError) { - return Math.Abs(_wattsPerSquareMeter - other._wattsPerSquareMeter) <= maxError._wattsPerSquareMeter; + return Math.Abs(AsBaseUnitWattsPerSquareMeter() - other.AsBaseUnitWattsPerSquareMeter()) <= maxError.AsBaseUnitWattsPerSquareMeter(); } public override int GetHashCode() { - return _wattsPerSquareMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -437,16 +452,20 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(IrradianceUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitWattsPerSquareMeter(); + switch (unit) { - case IrradianceUnit.KilowattPerSquareMeter: - return KilowattsPerSquareMeter; - case IrradianceUnit.WattPerSquareMeter: - return WattsPerSquareMeter; + case IrradianceUnit.KilowattPerSquareMeter: return (baseUnitValue) / 1e3d; + case IrradianceUnit.WattPerSquareMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -488,7 +507,11 @@ public static Irradiance Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -507,17 +530,24 @@ public static Irradiance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Irradiance Parse(string str, [CanBeNull] Culture culture) + public static Irradiance Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -543,16 +573,41 @@ public static bool TryParse([CanBeNull] string str, out Irradiance result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Irradiance result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Irradiance result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -565,6 +620,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -578,11 +634,14 @@ public static IrradianceUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static IrradianceUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -591,6 +650,8 @@ public static IrradianceUnit ParseUnit(string str, [CanBeNull] string cultureNam /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -603,18 +664,18 @@ public static IrradianceUnit ParseUnit(string str, [CanBeNull] string cultureNam #else public #endif - static IrradianceUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static IrradianceUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == IrradianceUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IrradianceUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -623,6 +684,7 @@ static IrradianceUnit ParseUnit(string str, IFormatProvider formatProvider = nul #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is WattPerSquareMeter /// @@ -634,7 +696,7 @@ static IrradianceUnit ParseUnit(string str, IFormatProvider formatProvider = nul /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -651,74 +713,130 @@ public string ToString(IrradianceUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(IrradianceUnit unit, [CanBeNull] Culture culture) + public string ToString( + IrradianceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(IrradianceUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + IrradianceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(IrradianceUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + IrradianceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Irradiance /// - public static Irradiance MaxValue - { - get - { - return new Irradiance(double.MaxValue); - } - } + public static Irradiance MaxValue => new Irradiance(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Irradiance /// - public static Irradiance MinValue + public static Irradiance MinValue => new Irradiance(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitWattsPerSquareMeter() { - get + if (Unit == IrradianceUnit.WattPerSquareMeter) { return _value; } + + switch (Unit) { - return new Irradiance(double.MinValue); - } - } - } + case IrradianceUnit.KilowattPerSquareMeter: return (_value) * 1e3d; + case IrradianceUnit.WattPerSquareMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(IrradianceUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs index 094ffd181f..e4988e1584 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Irradiation : IComparable, IComparable #endif { /// - /// Base unit of Irradiation. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly IrradiationUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _joulesPerSquareMeter; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Irradiation() : this(0) + public Irradiation() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Irradiation(double joulespersquaremeter) { - _joulesPerSquareMeter = Convert.ToDouble(joulespersquaremeter); + _value = Convert.ToDouble(joulespersquaremeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Irradiation(double numericValue, IrradiationUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit JoulePerSquareMeter. + /// + /// Value assuming base unit JoulePerSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Irradiation(long joulespersquaremeter) - { - _joulesPerSquareMeter = Convert.ToDouble(joulespersquaremeter); - } + Irradiation(long joulespersquaremeter) : this(Convert.ToDouble(joulespersquaremeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit JoulePerSquareMeter. + /// + /// Value assuming base unit JoulePerSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Irradiation(decimal joulespersquaremeter) - { - _joulesPerSquareMeter = Convert.ToDouble(joulespersquaremeter); - } + Irradiation(decimal joulespersquaremeter) : this(Convert.ToDouble(joulespersquaremeter), BaseUnit) { } #region Properties @@ -119,48 +156,30 @@ public Irradiation(double joulespersquaremeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static IrradiationUnit BaseUnit - { - get { return IrradiationUnit.JoulePerSquareMeter; } - } + public static IrradiationUnit BaseUnit => IrradiationUnit.JoulePerSquareMeter; /// /// All units of measurement for the Irradiation quantity. /// public static IrradiationUnit[] Units { get; } = Enum.GetValues(typeof(IrradiationUnit)).Cast().ToArray(); - /// /// Get Irradiation in JoulesPerSquareMeter. /// - public double JoulesPerSquareMeter - { - get { return _joulesPerSquareMeter; } - } - + public double JoulesPerSquareMeter => As(IrradiationUnit.JoulePerSquareMeter); /// /// Get Irradiation in KilowattHoursPerSquareMeter. /// - public double KilowattHoursPerSquareMeter - { - get { return (_joulesPerSquareMeter/3600d) / 1e3d; } - } - + public double KilowattHoursPerSquareMeter => As(IrradiationUnit.KilowattHourPerSquareMeter); /// /// Get Irradiation in WattHoursPerSquareMeter. /// - public double WattHoursPerSquareMeter - { - get { return _joulesPerSquareMeter/3600d; } - } + public double WattHoursPerSquareMeter => As(IrradiationUnit.WattHourPerSquareMeter); #endregion #region Static - public static Irradiation Zero - { - get { return new Irradiation(); } - } + public static Irradiation Zero => new Irradiation(0, BaseUnit); /// /// Get Irradiation from JoulesPerSquareMeter. @@ -168,17 +187,13 @@ public static Irradiation Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Irradiation FromJoulesPerSquareMeter(double joulespersquaremeter) - { - double value = (double) joulespersquaremeter; - return new Irradiation(value); - } #else public static Irradiation FromJoulesPerSquareMeter(QuantityValue joulespersquaremeter) +#endif { double value = (double) joulespersquaremeter; - return new Irradiation((value)); + return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); } -#endif /// /// Get Irradiation from KilowattHoursPerSquareMeter. @@ -186,17 +201,13 @@ public static Irradiation FromJoulesPerSquareMeter(QuantityValue joulespersquare #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Irradiation FromKilowattHoursPerSquareMeter(double kilowatthourspersquaremeter) - { - double value = (double) kilowatthourspersquaremeter; - return new Irradiation((value*3600d) * 1e3d); - } #else public static Irradiation FromKilowattHoursPerSquareMeter(QuantityValue kilowatthourspersquaremeter) +#endif { double value = (double) kilowatthourspersquaremeter; - return new Irradiation(((value*3600d) * 1e3d)); + return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); } -#endif /// /// Get Irradiation from WattHoursPerSquareMeter. @@ -204,17 +215,13 @@ public static Irradiation FromKilowattHoursPerSquareMeter(QuantityValue kilowatt #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Irradiation FromWattHoursPerSquareMeter(double watthourspersquaremeter) - { - double value = (double) watthourspersquaremeter; - return new Irradiation(value*3600d); - } #else public static Irradiation FromWattHoursPerSquareMeter(QuantityValue watthourspersquaremeter) +#endif { double value = (double) watthourspersquaremeter; - return new Irradiation((value*3600d)); + return new Irradiation(value, IrradiationUnit.WattHourPerSquareMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -279,18 +286,7 @@ public static Irradiation From(double value, IrradiationUnit fromUnit) public static Irradiation From(QuantityValue value, IrradiationUnit fromUnit) #endif { - switch (fromUnit) - { - case IrradiationUnit.JoulePerSquareMeter: - return FromJoulesPerSquareMeter(value); - case IrradiationUnit.KilowattHourPerSquareMeter: - return FromKilowattHoursPerSquareMeter(value); - case IrradiationUnit.WattHourPerSquareMeter: - return FromWattHoursPerSquareMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Irradiation((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -307,18 +303,8 @@ public static Irradiation From(QuantityValue value, IrradiationUnit fromUnit) { return null; } - switch (fromUnit) - { - case IrradiationUnit.JoulePerSquareMeter: - return FromJoulesPerSquareMeter(value.Value); - case IrradiationUnit.KilowattHourPerSquareMeter: - return FromKilowattHoursPerSquareMeter(value.Value); - case IrradiationUnit.WattHourPerSquareMeter: - return FromWattHoursPerSquareMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Irradiation((double)value.Value, fromUnit); } #endif @@ -337,12 +323,29 @@ public static string GetAbbreviation(IrradiationUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(IrradiationUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + IrradiationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -353,37 +356,37 @@ public static string GetAbbreviation(IrradiationUnit unit, [CanBeNull] Culture c #if !WINDOWS_UWP public static Irradiation operator -(Irradiation right) { - return new Irradiation(-right._joulesPerSquareMeter); + return new Irradiation(-right.Value, right.Unit); } public static Irradiation operator +(Irradiation left, Irradiation right) { - return new Irradiation(left._joulesPerSquareMeter + right._joulesPerSquareMeter); + return new Irradiation(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Irradiation operator -(Irradiation left, Irradiation right) { - return new Irradiation(left._joulesPerSquareMeter - right._joulesPerSquareMeter); + return new Irradiation(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Irradiation operator *(double left, Irradiation right) { - return new Irradiation(left*right._joulesPerSquareMeter); + return new Irradiation(left * right.Value, right.Unit); } public static Irradiation operator *(Irradiation left, double right) { - return new Irradiation(left._joulesPerSquareMeter*(double)right); + return new Irradiation(left.Value * right, left.Unit); } public static Irradiation operator /(Irradiation left, double right) { - return new Irradiation(left._joulesPerSquareMeter/(double)right); + return new Irradiation(left.Value / right, left.Unit); } public static double operator /(Irradiation left, Irradiation right) { - return Convert.ToDouble(left._joulesPerSquareMeter/right._joulesPerSquareMeter); + return left.JoulesPerSquareMeter / right.JoulesPerSquareMeter; } #endif @@ -406,43 +409,43 @@ public int CompareTo(object obj) #endif int CompareTo(Irradiation other) { - return _joulesPerSquareMeter.CompareTo(other._joulesPerSquareMeter); + return AsBaseUnitJoulesPerSquareMeter().CompareTo(other.AsBaseUnitJoulesPerSquareMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Irradiation left, Irradiation right) { - return left._joulesPerSquareMeter <= right._joulesPerSquareMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Irradiation left, Irradiation right) { - return left._joulesPerSquareMeter >= right._joulesPerSquareMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Irradiation left, Irradiation right) { - return left._joulesPerSquareMeter < right._joulesPerSquareMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Irradiation left, Irradiation right) { - return left._joulesPerSquareMeter > right._joulesPerSquareMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Irradiation left, Irradiation right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerSquareMeter == right._joulesPerSquareMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Irradiation left, Irradiation right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerSquareMeter != right._joulesPerSquareMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -454,7 +457,7 @@ public override bool Equals(object obj) return false; } - return _joulesPerSquareMeter.Equals(((Irradiation) obj)._joulesPerSquareMeter); + return AsBaseUnitJoulesPerSquareMeter().Equals(((Irradiation) obj).AsBaseUnitJoulesPerSquareMeter()); } /// @@ -467,12 +470,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Irradiation other, Irradiation maxError) { - return Math.Abs(_joulesPerSquareMeter - other._joulesPerSquareMeter) <= maxError._joulesPerSquareMeter; + return Math.Abs(AsBaseUnitJoulesPerSquareMeter() - other.AsBaseUnitJoulesPerSquareMeter()) <= maxError.AsBaseUnitJoulesPerSquareMeter(); } public override int GetHashCode() { - return _joulesPerSquareMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -482,18 +485,21 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(IrradiationUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitJoulesPerSquareMeter(); + switch (unit) { - case IrradiationUnit.JoulePerSquareMeter: - return JoulesPerSquareMeter; - case IrradiationUnit.KilowattHourPerSquareMeter: - return KilowattHoursPerSquareMeter; - case IrradiationUnit.WattHourPerSquareMeter: - return WattHoursPerSquareMeter; + case IrradiationUnit.JoulePerSquareMeter: return baseUnitValue; + case IrradiationUnit.KilowattHourPerSquareMeter: return (baseUnitValue/3600d) / 1e3d; + case IrradiationUnit.WattHourPerSquareMeter: return baseUnitValue/3600d; default: throw new NotImplementedException("unit: " + unit); @@ -535,7 +541,11 @@ public static Irradiation Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -554,17 +564,24 @@ public static Irradiation Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Irradiation Parse(string str, [CanBeNull] Culture culture) + public static Irradiation Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -590,16 +607,41 @@ public static bool TryParse([CanBeNull] string str, out Irradiation result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Irradiation result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Irradiation result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -612,6 +654,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -625,11 +668,14 @@ public static IrradiationUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static IrradiationUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -638,6 +684,8 @@ public static IrradiationUnit ParseUnit(string str, [CanBeNull] string cultureNa /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -650,18 +698,18 @@ public static IrradiationUnit ParseUnit(string str, [CanBeNull] string cultureNa #else public #endif - static IrradiationUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static IrradiationUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == IrradiationUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized IrradiationUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -670,6 +718,7 @@ static IrradiationUnit ParseUnit(string str, IFormatProvider formatProvider = nu #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is JoulePerSquareMeter /// @@ -681,7 +730,7 @@ static IrradiationUnit ParseUnit(string str, IFormatProvider formatProvider = nu /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -698,74 +747,131 @@ public string ToString(IrradiationUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(IrradiationUnit unit, [CanBeNull] Culture culture) + public string ToString( + IrradiationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(IrradiationUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + IrradiationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(IrradiationUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + IrradiationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Irradiation /// - public static Irradiation MaxValue - { - get - { - return new Irradiation(double.MaxValue); - } - } + public static Irradiation MaxValue => new Irradiation(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Irradiation /// - public static Irradiation MinValue + public static Irradiation MinValue => new Irradiation(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitJoulesPerSquareMeter() { - get + if (Unit == IrradiationUnit.JoulePerSquareMeter) { return _value; } + + switch (Unit) { - return new Irradiation(double.MinValue); - } - } - } + case IrradiationUnit.JoulePerSquareMeter: return _value; + case IrradiationUnit.KilowattHourPerSquareMeter: return (_value*3600d) * 1e3d; + case IrradiationUnit.WattHourPerSquareMeter: return _value*3600d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(IrradiationUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs index 816bbd2955..6437b20a1f 100644 --- a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct KinematicViscosity : IComparable, IComparable - /// Base unit of KinematicViscosity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _squareMetersPerSecond; + private readonly KinematicViscosityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public KinematicViscosity() : this(0) + public KinematicViscosity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public KinematicViscosity(double squaremeterspersecond) { - _squareMetersPerSecond = Convert.ToDouble(squaremeterspersecond); + _value = Convert.ToDouble(squaremeterspersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + KinematicViscosity(double numericValue, KinematicViscosityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit SquareMeterPerSecond. + /// + /// Value assuming base unit SquareMeterPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - KinematicViscosity(long squaremeterspersecond) - { - _squareMetersPerSecond = Convert.ToDouble(squaremeterspersecond); - } + KinematicViscosity(long squaremeterspersecond) : this(Convert.ToDouble(squaremeterspersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit SquareMeterPerSecond. + /// + /// Value assuming base unit SquareMeterPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - KinematicViscosity(decimal squaremeterspersecond) - { - _squareMetersPerSecond = Convert.ToDouble(squaremeterspersecond); - } + KinematicViscosity(decimal squaremeterspersecond) : this(Convert.ToDouble(squaremeterspersecond), BaseUnit) { } #region Properties @@ -119,88 +156,50 @@ public KinematicViscosity(double squaremeterspersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static KinematicViscosityUnit BaseUnit - { - get { return KinematicViscosityUnit.SquareMeterPerSecond; } - } + public static KinematicViscosityUnit BaseUnit => KinematicViscosityUnit.SquareMeterPerSecond; /// /// All units of measurement for the KinematicViscosity quantity. /// public static KinematicViscosityUnit[] Units { get; } = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().ToArray(); - /// /// Get KinematicViscosity in Centistokes. /// - public double Centistokes - { - get { return (_squareMetersPerSecond*1e4) / 1e-2d; } - } - + public double Centistokes => As(KinematicViscosityUnit.Centistokes); /// /// Get KinematicViscosity in Decistokes. /// - public double Decistokes - { - get { return (_squareMetersPerSecond*1e4) / 1e-1d; } - } - + public double Decistokes => As(KinematicViscosityUnit.Decistokes); /// /// Get KinematicViscosity in Kilostokes. /// - public double Kilostokes - { - get { return (_squareMetersPerSecond*1e4) / 1e3d; } - } - + public double Kilostokes => As(KinematicViscosityUnit.Kilostokes); /// /// Get KinematicViscosity in Microstokes. /// - public double Microstokes - { - get { return (_squareMetersPerSecond*1e4) / 1e-6d; } - } - + public double Microstokes => As(KinematicViscosityUnit.Microstokes); /// /// Get KinematicViscosity in Millistokes. /// - public double Millistokes - { - get { return (_squareMetersPerSecond*1e4) / 1e-3d; } - } - + public double Millistokes => As(KinematicViscosityUnit.Millistokes); /// /// Get KinematicViscosity in Nanostokes. /// - public double Nanostokes - { - get { return (_squareMetersPerSecond*1e4) / 1e-9d; } - } - + public double Nanostokes => As(KinematicViscosityUnit.Nanostokes); /// /// Get KinematicViscosity in SquareMetersPerSecond. /// - public double SquareMetersPerSecond - { - get { return _squareMetersPerSecond; } - } - + public double SquareMetersPerSecond => As(KinematicViscosityUnit.SquareMeterPerSecond); /// /// Get KinematicViscosity in Stokes. /// - public double Stokes - { - get { return _squareMetersPerSecond*1e4; } - } + public double Stokes => As(KinematicViscosityUnit.Stokes); #endregion #region Static - public static KinematicViscosity Zero - { - get { return new KinematicViscosity(); } - } + public static KinematicViscosity Zero => new KinematicViscosity(0, BaseUnit); /// /// Get KinematicViscosity from Centistokes. @@ -208,17 +207,13 @@ public static KinematicViscosity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static KinematicViscosity FromCentistokes(double centistokes) - { - double value = (double) centistokes; - return new KinematicViscosity((value/1e4) * 1e-2d); - } #else public static KinematicViscosity FromCentistokes(QuantityValue centistokes) +#endif { double value = (double) centistokes; - return new KinematicViscosity(((value/1e4) * 1e-2d)); + return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); } -#endif /// /// Get KinematicViscosity from Decistokes. @@ -226,17 +221,13 @@ public static KinematicViscosity FromCentistokes(QuantityValue centistokes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static KinematicViscosity FromDecistokes(double decistokes) - { - double value = (double) decistokes; - return new KinematicViscosity((value/1e4) * 1e-1d); - } #else public static KinematicViscosity FromDecistokes(QuantityValue decistokes) +#endif { double value = (double) decistokes; - return new KinematicViscosity(((value/1e4) * 1e-1d)); + return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); } -#endif /// /// Get KinematicViscosity from Kilostokes. @@ -244,17 +235,13 @@ public static KinematicViscosity FromDecistokes(QuantityValue decistokes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static KinematicViscosity FromKilostokes(double kilostokes) - { - double value = (double) kilostokes; - return new KinematicViscosity((value/1e4) * 1e3d); - } #else public static KinematicViscosity FromKilostokes(QuantityValue kilostokes) +#endif { double value = (double) kilostokes; - return new KinematicViscosity(((value/1e4) * 1e3d)); + return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); } -#endif /// /// Get KinematicViscosity from Microstokes. @@ -262,17 +249,13 @@ public static KinematicViscosity FromKilostokes(QuantityValue kilostokes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static KinematicViscosity FromMicrostokes(double microstokes) - { - double value = (double) microstokes; - return new KinematicViscosity((value/1e4) * 1e-6d); - } #else public static KinematicViscosity FromMicrostokes(QuantityValue microstokes) +#endif { double value = (double) microstokes; - return new KinematicViscosity(((value/1e4) * 1e-6d)); + return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); } -#endif /// /// Get KinematicViscosity from Millistokes. @@ -280,17 +263,13 @@ public static KinematicViscosity FromMicrostokes(QuantityValue microstokes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static KinematicViscosity FromMillistokes(double millistokes) - { - double value = (double) millistokes; - return new KinematicViscosity((value/1e4) * 1e-3d); - } #else public static KinematicViscosity FromMillistokes(QuantityValue millistokes) +#endif { double value = (double) millistokes; - return new KinematicViscosity(((value/1e4) * 1e-3d)); + return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); } -#endif /// /// Get KinematicViscosity from Nanostokes. @@ -298,17 +277,13 @@ public static KinematicViscosity FromMillistokes(QuantityValue millistokes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static KinematicViscosity FromNanostokes(double nanostokes) - { - double value = (double) nanostokes; - return new KinematicViscosity((value/1e4) * 1e-9d); - } #else public static KinematicViscosity FromNanostokes(QuantityValue nanostokes) +#endif { double value = (double) nanostokes; - return new KinematicViscosity(((value/1e4) * 1e-9d)); + return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); } -#endif /// /// Get KinematicViscosity from SquareMetersPerSecond. @@ -316,17 +291,13 @@ public static KinematicViscosity FromNanostokes(QuantityValue nanostokes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static KinematicViscosity FromSquareMetersPerSecond(double squaremeterspersecond) - { - double value = (double) squaremeterspersecond; - return new KinematicViscosity(value); - } #else public static KinematicViscosity FromSquareMetersPerSecond(QuantityValue squaremeterspersecond) +#endif { double value = (double) squaremeterspersecond; - return new KinematicViscosity((value)); + return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); } -#endif /// /// Get KinematicViscosity from Stokes. @@ -334,17 +305,13 @@ public static KinematicViscosity FromSquareMetersPerSecond(QuantityValue squarem #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static KinematicViscosity FromStokes(double stokes) - { - double value = (double) stokes; - return new KinematicViscosity(value/1e4); - } #else public static KinematicViscosity FromStokes(QuantityValue stokes) +#endif { double value = (double) stokes; - return new KinematicViscosity((value/1e4)); + return new KinematicViscosity(value, KinematicViscosityUnit.Stokes); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -484,28 +451,7 @@ public static KinematicViscosity From(double value, KinematicViscosityUnit fromU public static KinematicViscosity From(QuantityValue value, KinematicViscosityUnit fromUnit) #endif { - switch (fromUnit) - { - case KinematicViscosityUnit.Centistokes: - return FromCentistokes(value); - case KinematicViscosityUnit.Decistokes: - return FromDecistokes(value); - case KinematicViscosityUnit.Kilostokes: - return FromKilostokes(value); - case KinematicViscosityUnit.Microstokes: - return FromMicrostokes(value); - case KinematicViscosityUnit.Millistokes: - return FromMillistokes(value); - case KinematicViscosityUnit.Nanostokes: - return FromNanostokes(value); - case KinematicViscosityUnit.SquareMeterPerSecond: - return FromSquareMetersPerSecond(value); - case KinematicViscosityUnit.Stokes: - return FromStokes(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new KinematicViscosity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -522,28 +468,8 @@ public static KinematicViscosity From(QuantityValue value, KinematicViscosityUni { return null; } - switch (fromUnit) - { - case KinematicViscosityUnit.Centistokes: - return FromCentistokes(value.Value); - case KinematicViscosityUnit.Decistokes: - return FromDecistokes(value.Value); - case KinematicViscosityUnit.Kilostokes: - return FromKilostokes(value.Value); - case KinematicViscosityUnit.Microstokes: - return FromMicrostokes(value.Value); - case KinematicViscosityUnit.Millistokes: - return FromMillistokes(value.Value); - case KinematicViscosityUnit.Nanostokes: - return FromNanostokes(value.Value); - case KinematicViscosityUnit.SquareMeterPerSecond: - return FromSquareMetersPerSecond(value.Value); - case KinematicViscosityUnit.Stokes: - return FromStokes(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new KinematicViscosity((double)value.Value, fromUnit); } #endif @@ -562,12 +488,29 @@ public static string GetAbbreviation(KinematicViscosityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(KinematicViscosityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + KinematicViscosityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -578,37 +521,37 @@ public static string GetAbbreviation(KinematicViscosityUnit unit, [CanBeNull] Cu #if !WINDOWS_UWP public static KinematicViscosity operator -(KinematicViscosity right) { - return new KinematicViscosity(-right._squareMetersPerSecond); + return new KinematicViscosity(-right.Value, right.Unit); } public static KinematicViscosity operator +(KinematicViscosity left, KinematicViscosity right) { - return new KinematicViscosity(left._squareMetersPerSecond + right._squareMetersPerSecond); + return new KinematicViscosity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static KinematicViscosity operator -(KinematicViscosity left, KinematicViscosity right) { - return new KinematicViscosity(left._squareMetersPerSecond - right._squareMetersPerSecond); + return new KinematicViscosity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static KinematicViscosity operator *(double left, KinematicViscosity right) { - return new KinematicViscosity(left*right._squareMetersPerSecond); + return new KinematicViscosity(left * right.Value, right.Unit); } public static KinematicViscosity operator *(KinematicViscosity left, double right) { - return new KinematicViscosity(left._squareMetersPerSecond*(double)right); + return new KinematicViscosity(left.Value * right, left.Unit); } public static KinematicViscosity operator /(KinematicViscosity left, double right) { - return new KinematicViscosity(left._squareMetersPerSecond/(double)right); + return new KinematicViscosity(left.Value / right, left.Unit); } public static double operator /(KinematicViscosity left, KinematicViscosity right) { - return Convert.ToDouble(left._squareMetersPerSecond/right._squareMetersPerSecond); + return left.SquareMetersPerSecond / right.SquareMetersPerSecond; } #endif @@ -631,43 +574,43 @@ public int CompareTo(object obj) #endif int CompareTo(KinematicViscosity other) { - return _squareMetersPerSecond.CompareTo(other._squareMetersPerSecond); + return AsBaseUnitSquareMetersPerSecond().CompareTo(other.AsBaseUnitSquareMetersPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(KinematicViscosity left, KinematicViscosity right) { - return left._squareMetersPerSecond <= right._squareMetersPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(KinematicViscosity left, KinematicViscosity right) { - return left._squareMetersPerSecond >= right._squareMetersPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(KinematicViscosity left, KinematicViscosity right) { - return left._squareMetersPerSecond < right._squareMetersPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(KinematicViscosity left, KinematicViscosity right) { - return left._squareMetersPerSecond > right._squareMetersPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(KinematicViscosity left, KinematicViscosity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._squareMetersPerSecond == right._squareMetersPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(KinematicViscosity left, KinematicViscosity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._squareMetersPerSecond != right._squareMetersPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -679,7 +622,7 @@ public override bool Equals(object obj) return false; } - return _squareMetersPerSecond.Equals(((KinematicViscosity) obj)._squareMetersPerSecond); + return AsBaseUnitSquareMetersPerSecond().Equals(((KinematicViscosity) obj).AsBaseUnitSquareMetersPerSecond()); } /// @@ -692,12 +635,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(KinematicViscosity other, KinematicViscosity maxError) { - return Math.Abs(_squareMetersPerSecond - other._squareMetersPerSecond) <= maxError._squareMetersPerSecond; + return Math.Abs(AsBaseUnitSquareMetersPerSecond() - other.AsBaseUnitSquareMetersPerSecond()) <= maxError.AsBaseUnitSquareMetersPerSecond(); } public override int GetHashCode() { - return _squareMetersPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -707,28 +650,26 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(KinematicViscosityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitSquareMetersPerSecond(); + switch (unit) { - case KinematicViscosityUnit.Centistokes: - return Centistokes; - case KinematicViscosityUnit.Decistokes: - return Decistokes; - case KinematicViscosityUnit.Kilostokes: - return Kilostokes; - case KinematicViscosityUnit.Microstokes: - return Microstokes; - case KinematicViscosityUnit.Millistokes: - return Millistokes; - case KinematicViscosityUnit.Nanostokes: - return Nanostokes; - case KinematicViscosityUnit.SquareMeterPerSecond: - return SquareMetersPerSecond; - case KinematicViscosityUnit.Stokes: - return Stokes; + case KinematicViscosityUnit.Centistokes: return (baseUnitValue*1e4) / 1e-2d; + case KinematicViscosityUnit.Decistokes: return (baseUnitValue*1e4) / 1e-1d; + case KinematicViscosityUnit.Kilostokes: return (baseUnitValue*1e4) / 1e3d; + case KinematicViscosityUnit.Microstokes: return (baseUnitValue*1e4) / 1e-6d; + case KinematicViscosityUnit.Millistokes: return (baseUnitValue*1e4) / 1e-3d; + case KinematicViscosityUnit.Nanostokes: return (baseUnitValue*1e4) / 1e-9d; + case KinematicViscosityUnit.SquareMeterPerSecond: return baseUnitValue; + case KinematicViscosityUnit.Stokes: return baseUnitValue*1e4; default: throw new NotImplementedException("unit: " + unit); @@ -770,7 +711,11 @@ public static KinematicViscosity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -789,17 +734,24 @@ public static KinematicViscosity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static KinematicViscosity Parse(string str, [CanBeNull] Culture culture) + public static KinematicViscosity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -825,16 +777,41 @@ public static bool TryParse([CanBeNull] string str, out KinematicViscosity resul /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out KinematicViscosity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out KinematicViscosity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -847,6 +824,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -860,11 +838,14 @@ public static KinematicViscosityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static KinematicViscosityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -873,6 +854,8 @@ public static KinematicViscosityUnit ParseUnit(string str, [CanBeNull] string cu /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -885,18 +868,18 @@ public static KinematicViscosityUnit ParseUnit(string str, [CanBeNull] string cu #else public #endif - static KinematicViscosityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static KinematicViscosityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == KinematicViscosityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized KinematicViscosityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -905,6 +888,7 @@ static KinematicViscosityUnit ParseUnit(string str, IFormatProvider formatProvid #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is SquareMeterPerSecond /// @@ -916,7 +900,7 @@ static KinematicViscosityUnit ParseUnit(string str, IFormatProvider formatProvid /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -933,74 +917,136 @@ public string ToString(KinematicViscosityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(KinematicViscosityUnit unit, [CanBeNull] Culture culture) + public string ToString( + KinematicViscosityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(KinematicViscosityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + KinematicViscosityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(KinematicViscosityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + KinematicViscosityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of KinematicViscosity /// - public static KinematicViscosity MaxValue - { - get - { - return new KinematicViscosity(double.MaxValue); - } - } + public static KinematicViscosity MaxValue => new KinematicViscosity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of KinematicViscosity /// - public static KinematicViscosity MinValue + public static KinematicViscosity MinValue => new KinematicViscosity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitSquareMetersPerSecond() { - get + if (Unit == KinematicViscosityUnit.SquareMeterPerSecond) { return _value; } + + switch (Unit) { - return new KinematicViscosity(double.MinValue); - } - } - } + case KinematicViscosityUnit.Centistokes: return (_value/1e4) * 1e-2d; + case KinematicViscosityUnit.Decistokes: return (_value/1e4) * 1e-1d; + case KinematicViscosityUnit.Kilostokes: return (_value/1e4) * 1e3d; + case KinematicViscosityUnit.Microstokes: return (_value/1e4) * 1e-6d; + case KinematicViscosityUnit.Millistokes: return (_value/1e4) * 1e-3d; + case KinematicViscosityUnit.Nanostokes: return (_value/1e4) * 1e-9d; + case KinematicViscosityUnit.SquareMeterPerSecond: return _value; + case KinematicViscosityUnit.Stokes: return _value/1e4; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(KinematicViscosityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs b/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs index 69583a230c..4652f866ec 100644 --- a/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LapseRate.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct LapseRate : IComparable, IComparable #endif { /// - /// Base unit of LapseRate. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LapseRateUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _degreesCelciusPerKilometer; + public LapseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public LapseRate() : this(0) + public LapseRate() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public LapseRate(double degreescelciusperkilometer) { - _degreesCelciusPerKilometer = Convert.ToDouble(degreescelciusperkilometer); + _value = Convert.ToDouble(degreescelciusperkilometer); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + LapseRate(double numericValue, LapseRateUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit DegreeCelsiusPerKilometer. + /// + /// Value assuming base unit DegreeCelsiusPerKilometer. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - LapseRate(long degreescelciusperkilometer) - { - _degreesCelciusPerKilometer = Convert.ToDouble(degreescelciusperkilometer); - } + LapseRate(long degreescelciusperkilometer) : this(Convert.ToDouble(degreescelciusperkilometer), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit DegreeCelsiusPerKilometer. + /// + /// Value assuming base unit DegreeCelsiusPerKilometer. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - LapseRate(decimal degreescelciusperkilometer) - { - _degreesCelciusPerKilometer = Convert.ToDouble(degreescelciusperkilometer); - } + LapseRate(decimal degreescelciusperkilometer) : this(Convert.ToDouble(degreescelciusperkilometer), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public LapseRate(double degreescelciusperkilometer) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static LapseRateUnit BaseUnit - { - get { return LapseRateUnit.DegreeCelsiusPerKilometer; } - } + public static LapseRateUnit BaseUnit => LapseRateUnit.DegreeCelsiusPerKilometer; /// /// All units of measurement for the LapseRate quantity. /// public static LapseRateUnit[] Units { get; } = Enum.GetValues(typeof(LapseRateUnit)).Cast().ToArray(); - /// /// Get LapseRate in DegreesCelciusPerKilometer. /// - public double DegreesCelciusPerKilometer - { - get { return _degreesCelciusPerKilometer; } - } + public double DegreesCelciusPerKilometer => As(LapseRateUnit.DegreeCelsiusPerKilometer); #endregion #region Static - public static LapseRate Zero - { - get { return new LapseRate(); } - } + public static LapseRate Zero => new LapseRate(0, BaseUnit); /// /// Get LapseRate from DegreesCelciusPerKilometer. @@ -152,17 +179,13 @@ public static LapseRate Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static LapseRate FromDegreesCelciusPerKilometer(double degreescelciusperkilometer) - { - double value = (double) degreescelciusperkilometer; - return new LapseRate(value); - } #else public static LapseRate FromDegreesCelciusPerKilometer(QuantityValue degreescelciusperkilometer) +#endif { double value = (double) degreescelciusperkilometer; - return new LapseRate((value)); + return new LapseRate(value, LapseRateUnit.DegreeCelsiusPerKilometer); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static LapseRate From(double value, LapseRateUnit fromUnit) public static LapseRate From(QuantityValue value, LapseRateUnit fromUnit) #endif { - switch (fromUnit) - { - case LapseRateUnit.DegreeCelsiusPerKilometer: - return FromDegreesCelciusPerKilometer(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new LapseRate((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static LapseRate From(QuantityValue value, LapseRateUnit fromUnit) { return null; } - switch (fromUnit) - { - case LapseRateUnit.DegreeCelsiusPerKilometer: - return FromDegreesCelciusPerKilometer(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new LapseRate((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(LapseRateUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(LapseRateUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + LapseRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(LapseRateUnit unit, [CanBeNull] Culture cul #if !WINDOWS_UWP public static LapseRate operator -(LapseRate right) { - return new LapseRate(-right._degreesCelciusPerKilometer); + return new LapseRate(-right.Value, right.Unit); } public static LapseRate operator +(LapseRate left, LapseRate right) { - return new LapseRate(left._degreesCelciusPerKilometer + right._degreesCelciusPerKilometer); + return new LapseRate(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static LapseRate operator -(LapseRate left, LapseRate right) { - return new LapseRate(left._degreesCelciusPerKilometer - right._degreesCelciusPerKilometer); + return new LapseRate(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static LapseRate operator *(double left, LapseRate right) { - return new LapseRate(left*right._degreesCelciusPerKilometer); + return new LapseRate(left * right.Value, right.Unit); } public static LapseRate operator *(LapseRate left, double right) { - return new LapseRate(left._degreesCelciusPerKilometer*(double)right); + return new LapseRate(left.Value * right, left.Unit); } public static LapseRate operator /(LapseRate left, double right) { - return new LapseRate(left._degreesCelciusPerKilometer/(double)right); + return new LapseRate(left.Value / right, left.Unit); } public static double operator /(LapseRate left, LapseRate right) { - return Convert.ToDouble(left._degreesCelciusPerKilometer/right._degreesCelciusPerKilometer); + return left.DegreesCelciusPerKilometer / right.DegreesCelciusPerKilometer; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(LapseRate other) { - return _degreesCelciusPerKilometer.CompareTo(other._degreesCelciusPerKilometer); + return AsBaseUnitDegreesCelciusPerKilometer().CompareTo(other.AsBaseUnitDegreesCelciusPerKilometer()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(LapseRate left, LapseRate right) { - return left._degreesCelciusPerKilometer <= right._degreesCelciusPerKilometer; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(LapseRate left, LapseRate right) { - return left._degreesCelciusPerKilometer >= right._degreesCelciusPerKilometer; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(LapseRate left, LapseRate right) { - return left._degreesCelciusPerKilometer < right._degreesCelciusPerKilometer; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(LapseRate left, LapseRate right) { - return left._degreesCelciusPerKilometer > right._degreesCelciusPerKilometer; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(LapseRate left, LapseRate right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._degreesCelciusPerKilometer == right._degreesCelciusPerKilometer; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(LapseRate left, LapseRate right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._degreesCelciusPerKilometer != right._degreesCelciusPerKilometer; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _degreesCelciusPerKilometer.Equals(((LapseRate) obj)._degreesCelciusPerKilometer); + return AsBaseUnitDegreesCelciusPerKilometer().Equals(((LapseRate) obj).AsBaseUnitDegreesCelciusPerKilometer()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(LapseRate other, LapseRate maxError) { - return Math.Abs(_degreesCelciusPerKilometer - other._degreesCelciusPerKilometer) <= maxError._degreesCelciusPerKilometer; + return Math.Abs(AsBaseUnitDegreesCelciusPerKilometer() - other.AsBaseUnitDegreesCelciusPerKilometer()) <= maxError.AsBaseUnitDegreesCelciusPerKilometer(); } public override int GetHashCode() { - return _degreesCelciusPerKilometer.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(LapseRateUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitDegreesCelciusPerKilometer(); + switch (unit) { - case LapseRateUnit.DegreeCelsiusPerKilometer: - return DegreesCelciusPerKilometer; + case LapseRateUnit.DegreeCelsiusPerKilometer: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static LapseRate Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static LapseRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static LapseRate Parse(string str, [CanBeNull] Culture culture) + public static LapseRate Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out LapseRate result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out LapseRate result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out LapseRate result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static LapseRateUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static LapseRateUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static LapseRateUnit ParseUnit(string str, [CanBeNull] string cultureName /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static LapseRateUnit ParseUnit(string str, [CanBeNull] string cultureName #else public #endif - static LapseRateUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static LapseRateUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == LapseRateUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LapseRateUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static LapseRateUnit ParseUnit(string str, IFormatProvider formatProvider = null #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is DegreeCelsiusPerKilometer /// @@ -587,7 +662,7 @@ static LapseRateUnit ParseUnit(string str, IFormatProvider formatProvider = null /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(LapseRateUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(LapseRateUnit unit, [CanBeNull] Culture culture) + public string ToString( + LapseRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(LapseRateUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + LapseRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(LapseRateUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + LapseRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of LapseRate /// - public static LapseRate MaxValue - { - get - { - return new LapseRate(double.MaxValue); - } - } + public static LapseRate MaxValue => new LapseRate(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of LapseRate /// - public static LapseRate MinValue + public static LapseRate MinValue => new LapseRate(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitDegreesCelciusPerKilometer() { - get + if (Unit == LapseRateUnit.DegreeCelsiusPerKilometer) { return _value; } + + switch (Unit) { - return new LapseRate(double.MinValue); - } - } - } + case LapseRateUnit.DegreeCelsiusPerKilometer: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(LapseRateUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Length.g.cs b/UnitsNet/GeneratedCode/Quantities/Length.g.cs index 57b858fd9f..ce874905c2 100644 --- a/UnitsNet/GeneratedCode/Quantities/Length.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Length.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Length : IComparable, IComparable #endif { /// - /// Base unit of Length. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _meters; + private readonly LengthUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Length() : this(0) + public Length() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Length(double meters) { - _meters = Convert.ToDouble(meters); + _value = Convert.ToDouble(meters); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Length(double numericValue, LengthUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Meter. + /// + /// Value assuming base unit Meter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Length(long meters) - { - _meters = Convert.ToDouble(meters); - } + Length(long meters) : this(Convert.ToDouble(meters), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Meter. + /// + /// Value assuming base unit Meter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Length(decimal meters) - { - _meters = Convert.ToDouble(meters); - } + Length(decimal meters) : this(Convert.ToDouble(meters), BaseUnit) { } #region Properties @@ -119,200 +156,106 @@ public Length(double meters) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static LengthUnit BaseUnit - { - get { return LengthUnit.Meter; } - } + public static LengthUnit BaseUnit => LengthUnit.Meter; /// /// All units of measurement for the Length quantity. /// public static LengthUnit[] Units { get; } = Enum.GetValues(typeof(LengthUnit)).Cast().ToArray(); - /// /// Get Length in Centimeters. /// - public double Centimeters - { - get { return (_meters) / 1e-2d; } - } - + public double Centimeters => As(LengthUnit.Centimeter); /// /// Get Length in Decimeters. /// - public double Decimeters - { - get { return (_meters) / 1e-1d; } - } - + public double Decimeters => As(LengthUnit.Decimeter); /// /// Get Length in DtpPicas. /// - public double DtpPicas - { - get { return _meters*236.220472441; } - } - + public double DtpPicas => As(LengthUnit.DtpPica); /// /// Get Length in DtpPoints. /// - public double DtpPoints - { - get { return (_meters/2.54e-2)*72; } - } - + public double DtpPoints => As(LengthUnit.DtpPoint); /// /// Get Length in Fathoms. /// - public double Fathoms - { - get { return _meters/1.8288; } - } - + public double Fathoms => As(LengthUnit.Fathom); /// /// Get Length in Feet. /// - public double Feet - { - get { return _meters/0.3048; } - } - + public double Feet => As(LengthUnit.Foot); /// /// Get Length in Inches. /// - public double Inches - { - get { return _meters/2.54e-2; } - } - + public double Inches => As(LengthUnit.Inch); /// /// Get Length in Kilometers. /// - public double Kilometers - { - get { return (_meters) / 1e3d; } - } - + public double Kilometers => As(LengthUnit.Kilometer); /// /// Get Length in Meters. /// - public double Meters - { - get { return _meters; } - } - + public double Meters => As(LengthUnit.Meter); /// /// Get Length in Microinches. /// - public double Microinches - { - get { return _meters/2.54e-8; } - } - + public double Microinches => As(LengthUnit.Microinch); /// /// Get Length in Micrometers. /// - public double Micrometers - { - get { return (_meters) / 1e-6d; } - } - + public double Micrometers => As(LengthUnit.Micrometer); /// /// Get Length in Mils. /// - public double Mils - { - get { return _meters/2.54e-5; } - } - + public double Mils => As(LengthUnit.Mil); /// /// Get Length in Miles. /// - public double Miles - { - get { return _meters/1609.34; } - } - + public double Miles => As(LengthUnit.Mile); /// /// Get Length in Millimeters. /// - public double Millimeters - { - get { return (_meters) / 1e-3d; } - } - + public double Millimeters => As(LengthUnit.Millimeter); /// /// Get Length in Nanometers. /// - public double Nanometers - { - get { return (_meters) / 1e-9d; } - } - + public double Nanometers => As(LengthUnit.Nanometer); /// /// Get Length in NauticalMiles. /// - public double NauticalMiles - { - get { return _meters/1852; } - } - + public double NauticalMiles => As(LengthUnit.NauticalMile); /// /// Get Length in PrinterPicas. /// - public double PrinterPicas - { - get { return _meters*237.106301584; } - } - + public double PrinterPicas => As(LengthUnit.PrinterPica); /// /// Get Length in PrinterPoints. /// - public double PrinterPoints - { - get { return (_meters/2.54e-2)*72.27; } - } - + public double PrinterPoints => As(LengthUnit.PrinterPoint); /// /// Get Length in Shackles. /// - public double Shackles - { - get { return _meters/27.432; } - } - + public double Shackles => As(LengthUnit.Shackle); /// /// Get Length in Twips. /// - public double Twips - { - get { return _meters*56692.913385826; } - } - + public double Twips => As(LengthUnit.Twip); /// /// Get Length in UsSurveyFeet. /// - public double UsSurveyFeet - { - get { return _meters*3937/1200; } - } - + public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); /// /// Get Length in Yards. /// - public double Yards - { - get { return _meters/0.9144; } - } + public double Yards => As(LengthUnit.Yard); #endregion #region Static - public static Length Zero - { - get { return new Length(); } - } + public static Length Zero => new Length(0, BaseUnit); /// /// Get Length from Centimeters. @@ -320,17 +263,13 @@ public static Length Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromCentimeters(double centimeters) - { - double value = (double) centimeters; - return new Length((value) * 1e-2d); - } #else public static Length FromCentimeters(QuantityValue centimeters) +#endif { double value = (double) centimeters; - return new Length(((value) * 1e-2d)); + return new Length(value, LengthUnit.Centimeter); } -#endif /// /// Get Length from Decimeters. @@ -338,17 +277,13 @@ public static Length FromCentimeters(QuantityValue centimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromDecimeters(double decimeters) - { - double value = (double) decimeters; - return new Length((value) * 1e-1d); - } #else public static Length FromDecimeters(QuantityValue decimeters) +#endif { double value = (double) decimeters; - return new Length(((value) * 1e-1d)); + return new Length(value, LengthUnit.Decimeter); } -#endif /// /// Get Length from DtpPicas. @@ -356,17 +291,13 @@ public static Length FromDecimeters(QuantityValue decimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromDtpPicas(double dtppicas) - { - double value = (double) dtppicas; - return new Length(value/236.220472441); - } #else public static Length FromDtpPicas(QuantityValue dtppicas) +#endif { double value = (double) dtppicas; - return new Length((value/236.220472441)); + return new Length(value, LengthUnit.DtpPica); } -#endif /// /// Get Length from DtpPoints. @@ -374,17 +305,13 @@ public static Length FromDtpPicas(QuantityValue dtppicas) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromDtpPoints(double dtppoints) - { - double value = (double) dtppoints; - return new Length((value/72)*2.54e-2); - } #else public static Length FromDtpPoints(QuantityValue dtppoints) +#endif { double value = (double) dtppoints; - return new Length(((value/72)*2.54e-2)); + return new Length(value, LengthUnit.DtpPoint); } -#endif /// /// Get Length from Fathoms. @@ -392,17 +319,13 @@ public static Length FromDtpPoints(QuantityValue dtppoints) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromFathoms(double fathoms) - { - double value = (double) fathoms; - return new Length(value*1.8288); - } #else public static Length FromFathoms(QuantityValue fathoms) +#endif { double value = (double) fathoms; - return new Length((value*1.8288)); + return new Length(value, LengthUnit.Fathom); } -#endif /// /// Get Length from Feet. @@ -410,17 +333,13 @@ public static Length FromFathoms(QuantityValue fathoms) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromFeet(double feet) - { - double value = (double) feet; - return new Length(value*0.3048); - } #else public static Length FromFeet(QuantityValue feet) +#endif { double value = (double) feet; - return new Length((value*0.3048)); + return new Length(value, LengthUnit.Foot); } -#endif /// /// Get Length from Inches. @@ -428,17 +347,13 @@ public static Length FromFeet(QuantityValue feet) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromInches(double inches) - { - double value = (double) inches; - return new Length(value*2.54e-2); - } #else public static Length FromInches(QuantityValue inches) +#endif { double value = (double) inches; - return new Length((value*2.54e-2)); + return new Length(value, LengthUnit.Inch); } -#endif /// /// Get Length from Kilometers. @@ -446,17 +361,13 @@ public static Length FromInches(QuantityValue inches) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromKilometers(double kilometers) - { - double value = (double) kilometers; - return new Length((value) * 1e3d); - } #else public static Length FromKilometers(QuantityValue kilometers) +#endif { double value = (double) kilometers; - return new Length(((value) * 1e3d)); + return new Length(value, LengthUnit.Kilometer); } -#endif /// /// Get Length from Meters. @@ -464,17 +375,13 @@ public static Length FromKilometers(QuantityValue kilometers) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromMeters(double meters) - { - double value = (double) meters; - return new Length(value); - } #else public static Length FromMeters(QuantityValue meters) +#endif { double value = (double) meters; - return new Length((value)); + return new Length(value, LengthUnit.Meter); } -#endif /// /// Get Length from Microinches. @@ -482,17 +389,13 @@ public static Length FromMeters(QuantityValue meters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromMicroinches(double microinches) - { - double value = (double) microinches; - return new Length(value*2.54e-8); - } #else public static Length FromMicroinches(QuantityValue microinches) +#endif { double value = (double) microinches; - return new Length((value*2.54e-8)); + return new Length(value, LengthUnit.Microinch); } -#endif /// /// Get Length from Micrometers. @@ -500,17 +403,13 @@ public static Length FromMicroinches(QuantityValue microinches) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromMicrometers(double micrometers) - { - double value = (double) micrometers; - return new Length((value) * 1e-6d); - } #else public static Length FromMicrometers(QuantityValue micrometers) +#endif { double value = (double) micrometers; - return new Length(((value) * 1e-6d)); + return new Length(value, LengthUnit.Micrometer); } -#endif /// /// Get Length from Mils. @@ -518,17 +417,13 @@ public static Length FromMicrometers(QuantityValue micrometers) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromMils(double mils) - { - double value = (double) mils; - return new Length(value*2.54e-5); - } #else public static Length FromMils(QuantityValue mils) +#endif { double value = (double) mils; - return new Length((value*2.54e-5)); + return new Length(value, LengthUnit.Mil); } -#endif /// /// Get Length from Miles. @@ -536,17 +431,13 @@ public static Length FromMils(QuantityValue mils) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromMiles(double miles) - { - double value = (double) miles; - return new Length(value*1609.34); - } #else public static Length FromMiles(QuantityValue miles) +#endif { double value = (double) miles; - return new Length((value*1609.34)); + return new Length(value, LengthUnit.Mile); } -#endif /// /// Get Length from Millimeters. @@ -554,17 +445,13 @@ public static Length FromMiles(QuantityValue miles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromMillimeters(double millimeters) - { - double value = (double) millimeters; - return new Length((value) * 1e-3d); - } #else public static Length FromMillimeters(QuantityValue millimeters) +#endif { double value = (double) millimeters; - return new Length(((value) * 1e-3d)); + return new Length(value, LengthUnit.Millimeter); } -#endif /// /// Get Length from Nanometers. @@ -572,17 +459,13 @@ public static Length FromMillimeters(QuantityValue millimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromNanometers(double nanometers) - { - double value = (double) nanometers; - return new Length((value) * 1e-9d); - } #else public static Length FromNanometers(QuantityValue nanometers) +#endif { double value = (double) nanometers; - return new Length(((value) * 1e-9d)); + return new Length(value, LengthUnit.Nanometer); } -#endif /// /// Get Length from NauticalMiles. @@ -590,17 +473,13 @@ public static Length FromNanometers(QuantityValue nanometers) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromNauticalMiles(double nauticalmiles) - { - double value = (double) nauticalmiles; - return new Length(value*1852); - } #else public static Length FromNauticalMiles(QuantityValue nauticalmiles) +#endif { double value = (double) nauticalmiles; - return new Length((value*1852)); + return new Length(value, LengthUnit.NauticalMile); } -#endif /// /// Get Length from PrinterPicas. @@ -608,17 +487,13 @@ public static Length FromNauticalMiles(QuantityValue nauticalmiles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromPrinterPicas(double printerpicas) - { - double value = (double) printerpicas; - return new Length(value/237.106301584); - } #else public static Length FromPrinterPicas(QuantityValue printerpicas) +#endif { double value = (double) printerpicas; - return new Length((value/237.106301584)); + return new Length(value, LengthUnit.PrinterPica); } -#endif /// /// Get Length from PrinterPoints. @@ -626,17 +501,13 @@ public static Length FromPrinterPicas(QuantityValue printerpicas) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromPrinterPoints(double printerpoints) - { - double value = (double) printerpoints; - return new Length((value/72.27)*2.54e-2); - } #else public static Length FromPrinterPoints(QuantityValue printerpoints) +#endif { double value = (double) printerpoints; - return new Length(((value/72.27)*2.54e-2)); + return new Length(value, LengthUnit.PrinterPoint); } -#endif /// /// Get Length from Shackles. @@ -644,17 +515,13 @@ public static Length FromPrinterPoints(QuantityValue printerpoints) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromShackles(double shackles) - { - double value = (double) shackles; - return new Length(value*27.432); - } #else public static Length FromShackles(QuantityValue shackles) +#endif { double value = (double) shackles; - return new Length((value*27.432)); + return new Length(value, LengthUnit.Shackle); } -#endif /// /// Get Length from Twips. @@ -662,17 +529,13 @@ public static Length FromShackles(QuantityValue shackles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromTwips(double twips) - { - double value = (double) twips; - return new Length(value/56692.913385826); - } #else public static Length FromTwips(QuantityValue twips) +#endif { double value = (double) twips; - return new Length((value/56692.913385826)); + return new Length(value, LengthUnit.Twip); } -#endif /// /// Get Length from UsSurveyFeet. @@ -680,17 +543,13 @@ public static Length FromTwips(QuantityValue twips) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromUsSurveyFeet(double ussurveyfeet) - { - double value = (double) ussurveyfeet; - return new Length(value*1200/3937); - } #else public static Length FromUsSurveyFeet(QuantityValue ussurveyfeet) +#endif { double value = (double) ussurveyfeet; - return new Length((value*1200/3937)); + return new Length(value, LengthUnit.UsSurveyFoot); } -#endif /// /// Get Length from Yards. @@ -698,17 +557,13 @@ public static Length FromUsSurveyFeet(QuantityValue ussurveyfeet) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Length FromYards(double yards) - { - double value = (double) yards; - return new Length(value*0.9144); - } #else public static Length FromYards(QuantityValue yards) +#endif { double value = (double) yards; - return new Length((value*0.9144)); + return new Length(value, LengthUnit.Yard); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1058,56 +913,7 @@ public static Length From(double value, LengthUnit fromUnit) public static Length From(QuantityValue value, LengthUnit fromUnit) #endif { - switch (fromUnit) - { - case LengthUnit.Centimeter: - return FromCentimeters(value); - case LengthUnit.Decimeter: - return FromDecimeters(value); - case LengthUnit.DtpPica: - return FromDtpPicas(value); - case LengthUnit.DtpPoint: - return FromDtpPoints(value); - case LengthUnit.Fathom: - return FromFathoms(value); - case LengthUnit.Foot: - return FromFeet(value); - case LengthUnit.Inch: - return FromInches(value); - case LengthUnit.Kilometer: - return FromKilometers(value); - case LengthUnit.Meter: - return FromMeters(value); - case LengthUnit.Microinch: - return FromMicroinches(value); - case LengthUnit.Micrometer: - return FromMicrometers(value); - case LengthUnit.Mil: - return FromMils(value); - case LengthUnit.Mile: - return FromMiles(value); - case LengthUnit.Millimeter: - return FromMillimeters(value); - case LengthUnit.Nanometer: - return FromNanometers(value); - case LengthUnit.NauticalMile: - return FromNauticalMiles(value); - case LengthUnit.PrinterPica: - return FromPrinterPicas(value); - case LengthUnit.PrinterPoint: - return FromPrinterPoints(value); - case LengthUnit.Shackle: - return FromShackles(value); - case LengthUnit.Twip: - return FromTwips(value); - case LengthUnit.UsSurveyFoot: - return FromUsSurveyFeet(value); - case LengthUnit.Yard: - return FromYards(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Length((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1124,56 +930,8 @@ public static Length From(QuantityValue value, LengthUnit fromUnit) { return null; } - switch (fromUnit) - { - case LengthUnit.Centimeter: - return FromCentimeters(value.Value); - case LengthUnit.Decimeter: - return FromDecimeters(value.Value); - case LengthUnit.DtpPica: - return FromDtpPicas(value.Value); - case LengthUnit.DtpPoint: - return FromDtpPoints(value.Value); - case LengthUnit.Fathom: - return FromFathoms(value.Value); - case LengthUnit.Foot: - return FromFeet(value.Value); - case LengthUnit.Inch: - return FromInches(value.Value); - case LengthUnit.Kilometer: - return FromKilometers(value.Value); - case LengthUnit.Meter: - return FromMeters(value.Value); - case LengthUnit.Microinch: - return FromMicroinches(value.Value); - case LengthUnit.Micrometer: - return FromMicrometers(value.Value); - case LengthUnit.Mil: - return FromMils(value.Value); - case LengthUnit.Mile: - return FromMiles(value.Value); - case LengthUnit.Millimeter: - return FromMillimeters(value.Value); - case LengthUnit.Nanometer: - return FromNanometers(value.Value); - case LengthUnit.NauticalMile: - return FromNauticalMiles(value.Value); - case LengthUnit.PrinterPica: - return FromPrinterPicas(value.Value); - case LengthUnit.PrinterPoint: - return FromPrinterPoints(value.Value); - case LengthUnit.Shackle: - return FromShackles(value.Value); - case LengthUnit.Twip: - return FromTwips(value.Value); - case LengthUnit.UsSurveyFoot: - return FromUsSurveyFeet(value.Value); - case LengthUnit.Yard: - return FromYards(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Length((double)value.Value, fromUnit); } #endif @@ -1192,12 +950,29 @@ public static string GetAbbreviation(LengthUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(LengthUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + LengthUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1208,37 +983,37 @@ public static string GetAbbreviation(LengthUnit unit, [CanBeNull] Culture cultur #if !WINDOWS_UWP public static Length operator -(Length right) { - return new Length(-right._meters); + return new Length(-right.Value, right.Unit); } public static Length operator +(Length left, Length right) { - return new Length(left._meters + right._meters); + return new Length(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Length operator -(Length left, Length right) { - return new Length(left._meters - right._meters); + return new Length(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Length operator *(double left, Length right) { - return new Length(left*right._meters); + return new Length(left * right.Value, right.Unit); } public static Length operator *(Length left, double right) { - return new Length(left._meters*(double)right); + return new Length(left.Value * right, left.Unit); } public static Length operator /(Length left, double right) { - return new Length(left._meters/(double)right); + return new Length(left.Value / right, left.Unit); } public static double operator /(Length left, Length right) { - return Convert.ToDouble(left._meters/right._meters); + return left.Meters / right.Meters; } #endif @@ -1261,43 +1036,43 @@ public int CompareTo(object obj) #endif int CompareTo(Length other) { - return _meters.CompareTo(other._meters); + return AsBaseUnitMeters().CompareTo(other.AsBaseUnitMeters()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Length left, Length right) { - return left._meters <= right._meters; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Length left, Length right) { - return left._meters >= right._meters; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Length left, Length right) { - return left._meters < right._meters; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Length left, Length right) { - return left._meters > right._meters; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Length left, Length right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._meters == right._meters; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Length left, Length right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._meters != right._meters; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1309,7 +1084,7 @@ public override bool Equals(object obj) return false; } - return _meters.Equals(((Length) obj)._meters); + return AsBaseUnitMeters().Equals(((Length) obj).AsBaseUnitMeters()); } /// @@ -1322,12 +1097,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Length other, Length maxError) { - return Math.Abs(_meters - other._meters) <= maxError._meters; + return Math.Abs(AsBaseUnitMeters() - other.AsBaseUnitMeters()) <= maxError.AsBaseUnitMeters(); } public override int GetHashCode() { - return _meters.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1337,56 +1112,40 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(LengthUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitMeters(); + switch (unit) { - case LengthUnit.Centimeter: - return Centimeters; - case LengthUnit.Decimeter: - return Decimeters; - case LengthUnit.DtpPica: - return DtpPicas; - case LengthUnit.DtpPoint: - return DtpPoints; - case LengthUnit.Fathom: - return Fathoms; - case LengthUnit.Foot: - return Feet; - case LengthUnit.Inch: - return Inches; - case LengthUnit.Kilometer: - return Kilometers; - case LengthUnit.Meter: - return Meters; - case LengthUnit.Microinch: - return Microinches; - case LengthUnit.Micrometer: - return Micrometers; - case LengthUnit.Mil: - return Mils; - case LengthUnit.Mile: - return Miles; - case LengthUnit.Millimeter: - return Millimeters; - case LengthUnit.Nanometer: - return Nanometers; - case LengthUnit.NauticalMile: - return NauticalMiles; - case LengthUnit.PrinterPica: - return PrinterPicas; - case LengthUnit.PrinterPoint: - return PrinterPoints; - case LengthUnit.Shackle: - return Shackles; - case LengthUnit.Twip: - return Twips; - case LengthUnit.UsSurveyFoot: - return UsSurveyFeet; - case LengthUnit.Yard: - return Yards; + case LengthUnit.Centimeter: return (baseUnitValue) / 1e-2d; + case LengthUnit.Decimeter: return (baseUnitValue) / 1e-1d; + case LengthUnit.DtpPica: return baseUnitValue*236.220472441; + case LengthUnit.DtpPoint: return (baseUnitValue/2.54e-2)*72; + case LengthUnit.Fathom: return baseUnitValue/1.8288; + case LengthUnit.Foot: return baseUnitValue/0.3048; + case LengthUnit.Inch: return baseUnitValue/2.54e-2; + case LengthUnit.Kilometer: return (baseUnitValue) / 1e3d; + case LengthUnit.Meter: return baseUnitValue; + case LengthUnit.Microinch: return baseUnitValue/2.54e-8; + case LengthUnit.Micrometer: return (baseUnitValue) / 1e-6d; + case LengthUnit.Mil: return baseUnitValue/2.54e-5; + case LengthUnit.Mile: return baseUnitValue/1609.34; + case LengthUnit.Millimeter: return (baseUnitValue) / 1e-3d; + case LengthUnit.Nanometer: return (baseUnitValue) / 1e-9d; + case LengthUnit.NauticalMile: return baseUnitValue/1852; + case LengthUnit.PrinterPica: return baseUnitValue*237.106301584; + case LengthUnit.PrinterPoint: return (baseUnitValue/2.54e-2)*72.27; + case LengthUnit.Shackle: return baseUnitValue/27.432; + case LengthUnit.Twip: return baseUnitValue*56692.913385826; + case LengthUnit.UsSurveyFoot: return baseUnitValue*3937/1200; + case LengthUnit.Yard: return baseUnitValue/0.9144; default: throw new NotImplementedException("unit: " + unit); @@ -1428,7 +1187,11 @@ public static Length Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1447,17 +1210,24 @@ public static Length Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Length Parse(string str, [CanBeNull] Culture culture) + public static Length Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1483,16 +1253,41 @@ public static bool TryParse([CanBeNull] string str, out Length result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Length result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Length result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1505,6 +1300,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1518,11 +1314,14 @@ public static LengthUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static LengthUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1531,6 +1330,8 @@ public static LengthUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1543,18 +1344,18 @@ public static LengthUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static LengthUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static LengthUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == LengthUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LengthUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1563,6 +1364,7 @@ static LengthUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Meter /// @@ -1574,7 +1376,7 @@ static LengthUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1591,74 +1393,150 @@ public string ToString(LengthUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(LengthUnit unit, [CanBeNull] Culture culture) + public string ToString( + LengthUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(LengthUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + LengthUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(LengthUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + LengthUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Length /// - public static Length MaxValue - { - get - { - return new Length(double.MaxValue); - } - } + public static Length MaxValue => new Length(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Length /// - public static Length MinValue + public static Length MinValue => new Length(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitMeters() { - get + if (Unit == LengthUnit.Meter) { return _value; } + + switch (Unit) { - return new Length(double.MinValue); - } - } - } + case LengthUnit.Centimeter: return (_value) * 1e-2d; + case LengthUnit.Decimeter: return (_value) * 1e-1d; + case LengthUnit.DtpPica: return _value/236.220472441; + case LengthUnit.DtpPoint: return (_value/72)*2.54e-2; + case LengthUnit.Fathom: return _value*1.8288; + case LengthUnit.Foot: return _value*0.3048; + case LengthUnit.Inch: return _value*2.54e-2; + case LengthUnit.Kilometer: return (_value) * 1e3d; + case LengthUnit.Meter: return _value; + case LengthUnit.Microinch: return _value*2.54e-8; + case LengthUnit.Micrometer: return (_value) * 1e-6d; + case LengthUnit.Mil: return _value*2.54e-5; + case LengthUnit.Mile: return _value*1609.34; + case LengthUnit.Millimeter: return (_value) * 1e-3d; + case LengthUnit.Nanometer: return (_value) * 1e-9d; + case LengthUnit.NauticalMile: return _value*1852; + case LengthUnit.PrinterPica: return _value/237.106301584; + case LengthUnit.PrinterPoint: return (_value/72.27)*2.54e-2; + case LengthUnit.Shackle: return _value*27.432; + case LengthUnit.Twip: return _value/56692.913385826; + case LengthUnit.UsSurveyFoot: return _value*1200/3937; + case LengthUnit.Yard: return _value*0.9144; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(LengthUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Level.g.cs b/UnitsNet/GeneratedCode/Quantities/Level.g.cs index fb72281f73..b582080890 100644 --- a/UnitsNet/GeneratedCode/Quantities/Level.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Level.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Level : IComparable, IComparable #endif { /// - /// Base unit of Level. + /// The numeric value this quantity was constructed with. /// - private readonly double _decibels; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LevelUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Level() : this(0) + public Level() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Level(double decibels) { - _decibels = Convert.ToDouble(decibels); + _value = Convert.ToDouble(decibels); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Level(double numericValue, LevelUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Decibel. + /// + /// Value assuming base unit Decibel. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Level(long decibels) - { - _decibels = Convert.ToDouble(decibels); - } + Level(long decibels) : this(Convert.ToDouble(decibels), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Decibel. + /// + /// Value assuming base unit Decibel. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Level(decimal decibels) - { - _decibels = Convert.ToDouble(decibels); - } + Level(decimal decibels) : this(Convert.ToDouble(decibels), BaseUnit) { } #region Properties @@ -119,40 +156,26 @@ public Level(double decibels) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static LevelUnit BaseUnit - { - get { return LevelUnit.Decibel; } - } + public static LevelUnit BaseUnit => LevelUnit.Decibel; /// /// All units of measurement for the Level quantity. /// public static LevelUnit[] Units { get; } = Enum.GetValues(typeof(LevelUnit)).Cast().ToArray(); - /// /// Get Level in Decibels. /// - public double Decibels - { - get { return _decibels; } - } - + public double Decibels => As(LevelUnit.Decibel); /// /// Get Level in Nepers. /// - public double Nepers - { - get { return 0.115129254*_decibels; } - } + public double Nepers => As(LevelUnit.Neper); #endregion #region Static - public static Level Zero - { - get { return new Level(); } - } + public static Level Zero => new Level(0, BaseUnit); /// /// Get Level from Decibels. @@ -160,17 +183,13 @@ public static Level Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Level FromDecibels(double decibels) - { - double value = (double) decibels; - return new Level(value); - } #else public static Level FromDecibels(QuantityValue decibels) +#endif { double value = (double) decibels; - return new Level((value)); + return new Level(value, LevelUnit.Decibel); } -#endif /// /// Get Level from Nepers. @@ -178,17 +197,13 @@ public static Level FromDecibels(QuantityValue decibels) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Level FromNepers(double nepers) - { - double value = (double) nepers; - return new Level((1/0.115129254)*value); - } #else public static Level FromNepers(QuantityValue nepers) +#endif { double value = (double) nepers; - return new Level(((1/0.115129254)*value)); + return new Level(value, LevelUnit.Neper); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -238,16 +253,7 @@ public static Level From(double value, LevelUnit fromUnit) public static Level From(QuantityValue value, LevelUnit fromUnit) #endif { - switch (fromUnit) - { - case LevelUnit.Decibel: - return FromDecibels(value); - case LevelUnit.Neper: - return FromNepers(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Level((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -264,16 +270,8 @@ public static Level From(QuantityValue value, LevelUnit fromUnit) { return null; } - switch (fromUnit) - { - case LevelUnit.Decibel: - return FromDecibels(value.Value); - case LevelUnit.Neper: - return FromNepers(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Level((double)value.Value, fromUnit); } #endif @@ -292,12 +290,29 @@ public static string GetAbbreviation(LevelUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(LevelUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + LevelUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -308,45 +323,45 @@ public static string GetAbbreviation(LevelUnit unit, [CanBeNull] Culture culture #if !WINDOWS_UWP public static Level operator -(Level right) { - return new Level(-right._decibels); + return new Level(-right.Value, right.Unit); } 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._decibels/10) + Math.Pow(10, right._decibels/10))); + return new Level(10*Math.Log10(Math.Pow(10, left.Value/10) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/10)), left.Unit); } 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._decibels/10) - Math.Pow(10, right._decibels/10))); + return new Level(10*Math.Log10(Math.Pow(10, left.Value/10) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/10)), left.Unit); } public static Level operator *(double left, Level right) { // Logarithmic multiplication = addition - return new Level(left + right._decibels); + return new Level(left + right.Value, right.Unit); } public static Level operator *(Level left, double right) { // Logarithmic multiplication = addition - return new Level(left._decibels + (double)right); + return new Level(left.Value + (double)right, left.Unit); } public static Level operator /(Level left, double right) { // Logarithmic division = subtraction - return new Level(left._decibels - (double)right); + return new Level(left.Value - (double)right, left.Unit); } public static double operator /(Level left, Level right) { // Logarithmic division = subtraction - return Convert.ToDouble(left._decibels - right._decibels); + return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); } #endif @@ -369,43 +384,43 @@ public int CompareTo(object obj) #endif int CompareTo(Level other) { - return _decibels.CompareTo(other._decibels); + return AsBaseUnitDecibels().CompareTo(other.AsBaseUnitDecibels()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Level left, Level right) { - return left._decibels <= right._decibels; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Level left, Level right) { - return left._decibels >= right._decibels; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Level left, Level right) { - return left._decibels < right._decibels; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Level left, Level right) { - return left._decibels > right._decibels; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Level left, Level right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._decibels == right._decibels; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Level left, Level right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._decibels != right._decibels; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -417,7 +432,7 @@ public override bool Equals(object obj) return false; } - return _decibels.Equals(((Level) obj)._decibels); + return AsBaseUnitDecibels().Equals(((Level) obj).AsBaseUnitDecibels()); } /// @@ -430,12 +445,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Level other, Level maxError) { - return Math.Abs(_decibels - other._decibels) <= maxError._decibels; + return Math.Abs(AsBaseUnitDecibels() - other.AsBaseUnitDecibels()) <= maxError.AsBaseUnitDecibels(); } public override int GetHashCode() { - return _decibels.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -445,16 +460,20 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(LevelUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitDecibels(); + switch (unit) { - case LevelUnit.Decibel: - return Decibels; - case LevelUnit.Neper: - return Nepers; + case LevelUnit.Decibel: return baseUnitValue; + case LevelUnit.Neper: return 0.115129254*baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -496,7 +515,11 @@ public static Level Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -515,17 +538,24 @@ public static Level Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Level Parse(string str, [CanBeNull] Culture culture) + public static Level Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -551,16 +581,41 @@ public static bool TryParse([CanBeNull] string str, out Level result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Level result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Level result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -573,6 +628,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -586,11 +642,14 @@ public static LevelUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static LevelUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -599,6 +658,8 @@ public static LevelUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -611,18 +672,18 @@ public static LevelUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static LevelUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static LevelUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == LevelUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LevelUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -631,6 +692,7 @@ static LevelUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Decibel /// @@ -642,7 +704,7 @@ static LevelUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -659,74 +721,130 @@ public string ToString(LevelUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(LevelUnit unit, [CanBeNull] Culture culture) + public string ToString( + LevelUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(LevelUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + LevelUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(LevelUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + LevelUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Level /// - public static Level MaxValue - { - get - { - return new Level(double.MaxValue); - } - } + public static Level MaxValue => new Level(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Level /// - public static Level MinValue + public static Level MinValue => new Level(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitDecibels() { - get + if (Unit == LevelUnit.Decibel) { return _value; } + + switch (Unit) { - return new Level(double.MinValue); - } - } - } + case LevelUnit.Decibel: return _value; + case LevelUnit.Neper: return (1/0.115129254)*_value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(LevelUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs index b61138af46..1bfe689370 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct LinearDensity : IComparable, IComparable #endif { /// - /// Base unit of LinearDensity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LinearDensityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _kilogramsPerMeter; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public LinearDensity() : this(0) + public LinearDensity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public LinearDensity(double kilogramspermeter) { - _kilogramsPerMeter = Convert.ToDouble(kilogramspermeter); + _value = Convert.ToDouble(kilogramspermeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + LinearDensity(double numericValue, LinearDensityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerMeter. + /// + /// Value assuming base unit KilogramPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - LinearDensity(long kilogramspermeter) - { - _kilogramsPerMeter = Convert.ToDouble(kilogramspermeter); - } + LinearDensity(long kilogramspermeter) : this(Convert.ToDouble(kilogramspermeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerMeter. + /// + /// Value assuming base unit KilogramPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - LinearDensity(decimal kilogramspermeter) - { - _kilogramsPerMeter = Convert.ToDouble(kilogramspermeter); - } + LinearDensity(decimal kilogramspermeter) : this(Convert.ToDouble(kilogramspermeter), BaseUnit) { } #region Properties @@ -119,48 +156,30 @@ public LinearDensity(double kilogramspermeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static LinearDensityUnit BaseUnit - { - get { return LinearDensityUnit.KilogramPerMeter; } - } + public static LinearDensityUnit BaseUnit => LinearDensityUnit.KilogramPerMeter; /// /// All units of measurement for the LinearDensity quantity. /// public static LinearDensityUnit[] Units { get; } = Enum.GetValues(typeof(LinearDensityUnit)).Cast().ToArray(); - /// /// Get LinearDensity in GramsPerMeter. /// - public double GramsPerMeter - { - get { return _kilogramsPerMeter/1e-3; } - } - + public double GramsPerMeter => As(LinearDensityUnit.GramPerMeter); /// /// Get LinearDensity in KilogramsPerMeter. /// - public double KilogramsPerMeter - { - get { return (_kilogramsPerMeter/1e-3) / 1e3d; } - } - + public double KilogramsPerMeter => As(LinearDensityUnit.KilogramPerMeter); /// /// Get LinearDensity in PoundsPerFoot. /// - public double PoundsPerFoot - { - get { return _kilogramsPerMeter/1.48816394; } - } + public double PoundsPerFoot => As(LinearDensityUnit.PoundPerFoot); #endregion #region Static - public static LinearDensity Zero - { - get { return new LinearDensity(); } - } + public static LinearDensity Zero => new LinearDensity(0, BaseUnit); /// /// Get LinearDensity from GramsPerMeter. @@ -168,17 +187,13 @@ public static LinearDensity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static LinearDensity FromGramsPerMeter(double gramspermeter) - { - double value = (double) gramspermeter; - return new LinearDensity(value*1e-3); - } #else public static LinearDensity FromGramsPerMeter(QuantityValue gramspermeter) +#endif { double value = (double) gramspermeter; - return new LinearDensity((value*1e-3)); + return new LinearDensity(value, LinearDensityUnit.GramPerMeter); } -#endif /// /// Get LinearDensity from KilogramsPerMeter. @@ -186,17 +201,13 @@ public static LinearDensity FromGramsPerMeter(QuantityValue gramspermeter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static LinearDensity FromKilogramsPerMeter(double kilogramspermeter) - { - double value = (double) kilogramspermeter; - return new LinearDensity((value*1e-3) * 1e3d); - } #else public static LinearDensity FromKilogramsPerMeter(QuantityValue kilogramspermeter) +#endif { double value = (double) kilogramspermeter; - return new LinearDensity(((value*1e-3) * 1e3d)); + return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); } -#endif /// /// Get LinearDensity from PoundsPerFoot. @@ -204,17 +215,13 @@ public static LinearDensity FromKilogramsPerMeter(QuantityValue kilogramspermete #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static LinearDensity FromPoundsPerFoot(double poundsperfoot) - { - double value = (double) poundsperfoot; - return new LinearDensity(value*1.48816394); - } #else public static LinearDensity FromPoundsPerFoot(QuantityValue poundsperfoot) +#endif { double value = (double) poundsperfoot; - return new LinearDensity((value*1.48816394)); + return new LinearDensity(value, LinearDensityUnit.PoundPerFoot); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -279,18 +286,7 @@ public static LinearDensity From(double value, LinearDensityUnit fromUnit) public static LinearDensity From(QuantityValue value, LinearDensityUnit fromUnit) #endif { - switch (fromUnit) - { - case LinearDensityUnit.GramPerMeter: - return FromGramsPerMeter(value); - case LinearDensityUnit.KilogramPerMeter: - return FromKilogramsPerMeter(value); - case LinearDensityUnit.PoundPerFoot: - return FromPoundsPerFoot(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new LinearDensity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -307,18 +303,8 @@ public static LinearDensity From(QuantityValue value, LinearDensityUnit fromUnit { return null; } - switch (fromUnit) - { - case LinearDensityUnit.GramPerMeter: - return FromGramsPerMeter(value.Value); - case LinearDensityUnit.KilogramPerMeter: - return FromKilogramsPerMeter(value.Value); - case LinearDensityUnit.PoundPerFoot: - return FromPoundsPerFoot(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new LinearDensity((double)value.Value, fromUnit); } #endif @@ -337,12 +323,29 @@ public static string GetAbbreviation(LinearDensityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(LinearDensityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + LinearDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -353,37 +356,37 @@ public static string GetAbbreviation(LinearDensityUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static LinearDensity operator -(LinearDensity right) { - return new LinearDensity(-right._kilogramsPerMeter); + return new LinearDensity(-right.Value, right.Unit); } public static LinearDensity operator +(LinearDensity left, LinearDensity right) { - return new LinearDensity(left._kilogramsPerMeter + right._kilogramsPerMeter); + return new LinearDensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static LinearDensity operator -(LinearDensity left, LinearDensity right) { - return new LinearDensity(left._kilogramsPerMeter - right._kilogramsPerMeter); + return new LinearDensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static LinearDensity operator *(double left, LinearDensity right) { - return new LinearDensity(left*right._kilogramsPerMeter); + return new LinearDensity(left * right.Value, right.Unit); } public static LinearDensity operator *(LinearDensity left, double right) { - return new LinearDensity(left._kilogramsPerMeter*(double)right); + return new LinearDensity(left.Value * right, left.Unit); } public static LinearDensity operator /(LinearDensity left, double right) { - return new LinearDensity(left._kilogramsPerMeter/(double)right); + return new LinearDensity(left.Value / right, left.Unit); } public static double operator /(LinearDensity left, LinearDensity right) { - return Convert.ToDouble(left._kilogramsPerMeter/right._kilogramsPerMeter); + return left.KilogramsPerMeter / right.KilogramsPerMeter; } #endif @@ -406,43 +409,43 @@ public int CompareTo(object obj) #endif int CompareTo(LinearDensity other) { - return _kilogramsPerMeter.CompareTo(other._kilogramsPerMeter); + return AsBaseUnitKilogramsPerMeter().CompareTo(other.AsBaseUnitKilogramsPerMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(LinearDensity left, LinearDensity right) { - return left._kilogramsPerMeter <= right._kilogramsPerMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(LinearDensity left, LinearDensity right) { - return left._kilogramsPerMeter >= right._kilogramsPerMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(LinearDensity left, LinearDensity right) { - return left._kilogramsPerMeter < right._kilogramsPerMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(LinearDensity left, LinearDensity right) { - return left._kilogramsPerMeter > right._kilogramsPerMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(LinearDensity left, LinearDensity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerMeter == right._kilogramsPerMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(LinearDensity left, LinearDensity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerMeter != right._kilogramsPerMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -454,7 +457,7 @@ public override bool Equals(object obj) return false; } - return _kilogramsPerMeter.Equals(((LinearDensity) obj)._kilogramsPerMeter); + return AsBaseUnitKilogramsPerMeter().Equals(((LinearDensity) obj).AsBaseUnitKilogramsPerMeter()); } /// @@ -467,12 +470,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(LinearDensity other, LinearDensity maxError) { - return Math.Abs(_kilogramsPerMeter - other._kilogramsPerMeter) <= maxError._kilogramsPerMeter; + return Math.Abs(AsBaseUnitKilogramsPerMeter() - other.AsBaseUnitKilogramsPerMeter()) <= maxError.AsBaseUnitKilogramsPerMeter(); } public override int GetHashCode() { - return _kilogramsPerMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -482,18 +485,21 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(LinearDensityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitKilogramsPerMeter(); + switch (unit) { - case LinearDensityUnit.GramPerMeter: - return GramsPerMeter; - case LinearDensityUnit.KilogramPerMeter: - return KilogramsPerMeter; - case LinearDensityUnit.PoundPerFoot: - return PoundsPerFoot; + case LinearDensityUnit.GramPerMeter: return baseUnitValue/1e-3; + case LinearDensityUnit.KilogramPerMeter: return (baseUnitValue/1e-3) / 1e3d; + case LinearDensityUnit.PoundPerFoot: return baseUnitValue/1.48816394; default: throw new NotImplementedException("unit: " + unit); @@ -535,7 +541,11 @@ public static LinearDensity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -554,17 +564,24 @@ public static LinearDensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static LinearDensity Parse(string str, [CanBeNull] Culture culture) + public static LinearDensity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -590,16 +607,41 @@ public static bool TryParse([CanBeNull] string str, out LinearDensity result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out LinearDensity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out LinearDensity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -612,6 +654,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -625,11 +668,14 @@ public static LinearDensityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static LinearDensityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -638,6 +684,8 @@ public static LinearDensityUnit ParseUnit(string str, [CanBeNull] string culture /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -650,18 +698,18 @@ public static LinearDensityUnit ParseUnit(string str, [CanBeNull] string culture #else public #endif - static LinearDensityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static LinearDensityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == LinearDensityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LinearDensityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -670,6 +718,7 @@ static LinearDensityUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is KilogramPerMeter /// @@ -681,7 +730,7 @@ static LinearDensityUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -698,74 +747,131 @@ public string ToString(LinearDensityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(LinearDensityUnit unit, [CanBeNull] Culture culture) + public string ToString( + LinearDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(LinearDensityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + LinearDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(LinearDensityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + LinearDensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of LinearDensity /// - public static LinearDensity MaxValue - { - get - { - return new LinearDensity(double.MaxValue); - } - } + public static LinearDensity MaxValue => new LinearDensity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of LinearDensity /// - public static LinearDensity MinValue + public static LinearDensity MinValue => new LinearDensity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitKilogramsPerMeter() { - get + if (Unit == LinearDensityUnit.KilogramPerMeter) { return _value; } + + switch (Unit) { - return new LinearDensity(double.MinValue); - } - } - } + case LinearDensityUnit.GramPerMeter: return _value*1e-3; + case LinearDensityUnit.KilogramPerMeter: return (_value*1e-3) * 1e3d; + case LinearDensityUnit.PoundPerFoot: return _value*1.48816394; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(LinearDensityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs index 82eb5e194c..1f1e88f3d2 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct LuminousFlux : IComparable, IComparable #endif { /// - /// Base unit of LuminousFlux. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LuminousFluxUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _lumens; + public LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public LuminousFlux() : this(0) + public LuminousFlux() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public LuminousFlux(double lumens) { - _lumens = Convert.ToDouble(lumens); + _value = Convert.ToDouble(lumens); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + LuminousFlux(double numericValue, LuminousFluxUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Lumen. + /// + /// Value assuming base unit Lumen. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - LuminousFlux(long lumens) - { - _lumens = Convert.ToDouble(lumens); - } + LuminousFlux(long lumens) : this(Convert.ToDouble(lumens), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Lumen. + /// + /// Value assuming base unit Lumen. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - LuminousFlux(decimal lumens) - { - _lumens = Convert.ToDouble(lumens); - } + LuminousFlux(decimal lumens) : this(Convert.ToDouble(lumens), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public LuminousFlux(double lumens) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static LuminousFluxUnit BaseUnit - { - get { return LuminousFluxUnit.Lumen; } - } + public static LuminousFluxUnit BaseUnit => LuminousFluxUnit.Lumen; /// /// All units of measurement for the LuminousFlux quantity. /// public static LuminousFluxUnit[] Units { get; } = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().ToArray(); - /// /// Get LuminousFlux in Lumens. /// - public double Lumens - { - get { return _lumens; } - } + public double Lumens => As(LuminousFluxUnit.Lumen); #endregion #region Static - public static LuminousFlux Zero - { - get { return new LuminousFlux(); } - } + public static LuminousFlux Zero => new LuminousFlux(0, BaseUnit); /// /// Get LuminousFlux from Lumens. @@ -152,17 +179,13 @@ public static LuminousFlux Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static LuminousFlux FromLumens(double lumens) - { - double value = (double) lumens; - return new LuminousFlux(value); - } #else public static LuminousFlux FromLumens(QuantityValue lumens) +#endif { double value = (double) lumens; - return new LuminousFlux((value)); + return new LuminousFlux(value, LuminousFluxUnit.Lumen); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static LuminousFlux From(double value, LuminousFluxUnit fromUnit) public static LuminousFlux From(QuantityValue value, LuminousFluxUnit fromUnit) #endif { - switch (fromUnit) - { - case LuminousFluxUnit.Lumen: - return FromLumens(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new LuminousFlux((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static LuminousFlux From(QuantityValue value, LuminousFluxUnit fromUnit) { return null; } - switch (fromUnit) - { - case LuminousFluxUnit.Lumen: - return FromLumens(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new LuminousFlux((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(LuminousFluxUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(LuminousFluxUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + LuminousFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(LuminousFluxUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static LuminousFlux operator -(LuminousFlux right) { - return new LuminousFlux(-right._lumens); + return new LuminousFlux(-right.Value, right.Unit); } public static LuminousFlux operator +(LuminousFlux left, LuminousFlux right) { - return new LuminousFlux(left._lumens + right._lumens); + return new LuminousFlux(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static LuminousFlux operator -(LuminousFlux left, LuminousFlux right) { - return new LuminousFlux(left._lumens - right._lumens); + return new LuminousFlux(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static LuminousFlux operator *(double left, LuminousFlux right) { - return new LuminousFlux(left*right._lumens); + return new LuminousFlux(left * right.Value, right.Unit); } public static LuminousFlux operator *(LuminousFlux left, double right) { - return new LuminousFlux(left._lumens*(double)right); + return new LuminousFlux(left.Value * right, left.Unit); } public static LuminousFlux operator /(LuminousFlux left, double right) { - return new LuminousFlux(left._lumens/(double)right); + return new LuminousFlux(left.Value / right, left.Unit); } public static double operator /(LuminousFlux left, LuminousFlux right) { - return Convert.ToDouble(left._lumens/right._lumens); + return left.Lumens / right.Lumens; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(LuminousFlux other) { - return _lumens.CompareTo(other._lumens); + return AsBaseUnitLumens().CompareTo(other.AsBaseUnitLumens()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(LuminousFlux left, LuminousFlux right) { - return left._lumens <= right._lumens; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(LuminousFlux left, LuminousFlux right) { - return left._lumens >= right._lumens; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(LuminousFlux left, LuminousFlux right) { - return left._lumens < right._lumens; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(LuminousFlux left, LuminousFlux right) { - return left._lumens > right._lumens; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(LuminousFlux left, LuminousFlux right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._lumens == right._lumens; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(LuminousFlux left, LuminousFlux right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._lumens != right._lumens; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _lumens.Equals(((LuminousFlux) obj)._lumens); + return AsBaseUnitLumens().Equals(((LuminousFlux) obj).AsBaseUnitLumens()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(LuminousFlux other, LuminousFlux maxError) { - return Math.Abs(_lumens - other._lumens) <= maxError._lumens; + return Math.Abs(AsBaseUnitLumens() - other.AsBaseUnitLumens()) <= maxError.AsBaseUnitLumens(); } public override int GetHashCode() { - return _lumens.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(LuminousFluxUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitLumens(); + switch (unit) { - case LuminousFluxUnit.Lumen: - return Lumens; + case LuminousFluxUnit.Lumen: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static LuminousFlux Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static LuminousFlux Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static LuminousFlux Parse(string str, [CanBeNull] Culture culture) + public static LuminousFlux Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out LuminousFlux result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out LuminousFlux result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out LuminousFlux result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static LuminousFluxUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static LuminousFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static LuminousFluxUnit ParseUnit(string str, [CanBeNull] string cultureN /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static LuminousFluxUnit ParseUnit(string str, [CanBeNull] string cultureN #else public #endif - static LuminousFluxUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static LuminousFluxUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == LuminousFluxUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LuminousFluxUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static LuminousFluxUnit ParseUnit(string str, IFormatProvider formatProvider = n #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Lumen /// @@ -587,7 +662,7 @@ static LuminousFluxUnit ParseUnit(string str, IFormatProvider formatProvider = n /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(LuminousFluxUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(LuminousFluxUnit unit, [CanBeNull] Culture culture) + public string ToString( + LuminousFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(LuminousFluxUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + LuminousFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(LuminousFluxUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + LuminousFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of LuminousFlux /// - public static LuminousFlux MaxValue - { - get - { - return new LuminousFlux(double.MaxValue); - } - } + public static LuminousFlux MaxValue => new LuminousFlux(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of LuminousFlux /// - public static LuminousFlux MinValue + public static LuminousFlux MinValue => new LuminousFlux(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitLumens() { - get + if (Unit == LuminousFluxUnit.Lumen) { return _value; } + + switch (Unit) { - return new LuminousFlux(double.MinValue); - } - } - } + case LuminousFluxUnit.Lumen: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(LuminousFluxUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs index f09ed6c51d..b9dff32356 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct LuminousIntensity : IComparable, IComparable - /// Base unit of LuminousIntensity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly LuminousIntensityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _candela; + public LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public LuminousIntensity() : this(0) + public LuminousIntensity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public LuminousIntensity(double candela) { - _candela = Convert.ToDouble(candela); + _value = Convert.ToDouble(candela); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + LuminousIntensity(double numericValue, LuminousIntensityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Candela. + /// + /// Value assuming base unit Candela. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - LuminousIntensity(long candela) - { - _candela = Convert.ToDouble(candela); - } + LuminousIntensity(long candela) : this(Convert.ToDouble(candela), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Candela. + /// + /// Value assuming base unit Candela. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - LuminousIntensity(decimal candela) - { - _candela = Convert.ToDouble(candela); - } + LuminousIntensity(decimal candela) : this(Convert.ToDouble(candela), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public LuminousIntensity(double candela) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static LuminousIntensityUnit BaseUnit - { - get { return LuminousIntensityUnit.Candela; } - } + public static LuminousIntensityUnit BaseUnit => LuminousIntensityUnit.Candela; /// /// All units of measurement for the LuminousIntensity quantity. /// public static LuminousIntensityUnit[] Units { get; } = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().ToArray(); - /// /// Get LuminousIntensity in Candela. /// - public double Candela - { - get { return _candela; } - } + public double Candela => As(LuminousIntensityUnit.Candela); #endregion #region Static - public static LuminousIntensity Zero - { - get { return new LuminousIntensity(); } - } + public static LuminousIntensity Zero => new LuminousIntensity(0, BaseUnit); /// /// Get LuminousIntensity from Candela. @@ -152,17 +179,13 @@ public static LuminousIntensity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static LuminousIntensity FromCandela(double candela) - { - double value = (double) candela; - return new LuminousIntensity(value); - } #else public static LuminousIntensity FromCandela(QuantityValue candela) +#endif { double value = (double) candela; - return new LuminousIntensity((value)); + return new LuminousIntensity(value, LuminousIntensityUnit.Candela); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static LuminousIntensity From(double value, LuminousIntensityUnit fromUni public static LuminousIntensity From(QuantityValue value, LuminousIntensityUnit fromUnit) #endif { - switch (fromUnit) - { - case LuminousIntensityUnit.Candela: - return FromCandela(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new LuminousIntensity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static LuminousIntensity From(QuantityValue value, LuminousIntensityUnit { return null; } - switch (fromUnit) - { - case LuminousIntensityUnit.Candela: - return FromCandela(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new LuminousIntensity((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(LuminousIntensityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(LuminousIntensityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + LuminousIntensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(LuminousIntensityUnit unit, [CanBeNull] Cul #if !WINDOWS_UWP public static LuminousIntensity operator -(LuminousIntensity right) { - return new LuminousIntensity(-right._candela); + return new LuminousIntensity(-right.Value, right.Unit); } public static LuminousIntensity operator +(LuminousIntensity left, LuminousIntensity right) { - return new LuminousIntensity(left._candela + right._candela); + return new LuminousIntensity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static LuminousIntensity operator -(LuminousIntensity left, LuminousIntensity right) { - return new LuminousIntensity(left._candela - right._candela); + return new LuminousIntensity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static LuminousIntensity operator *(double left, LuminousIntensity right) { - return new LuminousIntensity(left*right._candela); + return new LuminousIntensity(left * right.Value, right.Unit); } public static LuminousIntensity operator *(LuminousIntensity left, double right) { - return new LuminousIntensity(left._candela*(double)right); + return new LuminousIntensity(left.Value * right, left.Unit); } public static LuminousIntensity operator /(LuminousIntensity left, double right) { - return new LuminousIntensity(left._candela/(double)right); + return new LuminousIntensity(left.Value / right, left.Unit); } public static double operator /(LuminousIntensity left, LuminousIntensity right) { - return Convert.ToDouble(left._candela/right._candela); + return left.Candela / right.Candela; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(LuminousIntensity other) { - return _candela.CompareTo(other._candela); + return AsBaseUnitCandela().CompareTo(other.AsBaseUnitCandela()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(LuminousIntensity left, LuminousIntensity right) { - return left._candela <= right._candela; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(LuminousIntensity left, LuminousIntensity right) { - return left._candela >= right._candela; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(LuminousIntensity left, LuminousIntensity right) { - return left._candela < right._candela; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(LuminousIntensity left, LuminousIntensity right) { - return left._candela > right._candela; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(LuminousIntensity left, LuminousIntensity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._candela == right._candela; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(LuminousIntensity left, LuminousIntensity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._candela != right._candela; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _candela.Equals(((LuminousIntensity) obj)._candela); + return AsBaseUnitCandela().Equals(((LuminousIntensity) obj).AsBaseUnitCandela()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(LuminousIntensity other, LuminousIntensity maxError) { - return Math.Abs(_candela - other._candela) <= maxError._candela; + return Math.Abs(AsBaseUnitCandela() - other.AsBaseUnitCandela()) <= maxError.AsBaseUnitCandela(); } public override int GetHashCode() { - return _candela.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(LuminousIntensityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitCandela(); + switch (unit) { - case LuminousIntensityUnit.Candela: - return Candela; + case LuminousIntensityUnit.Candela: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static LuminousIntensity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static LuminousIntensity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static LuminousIntensity Parse(string str, [CanBeNull] Culture culture) + public static LuminousIntensity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out LuminousIntensity result /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out LuminousIntensity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out LuminousIntensity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static LuminousIntensityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static LuminousIntensityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static LuminousIntensityUnit ParseUnit(string str, [CanBeNull] string cul /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static LuminousIntensityUnit ParseUnit(string str, [CanBeNull] string cul #else public #endif - static LuminousIntensityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static LuminousIntensityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == LuminousIntensityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized LuminousIntensityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static LuminousIntensityUnit ParseUnit(string str, IFormatProvider formatProvide #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Candela /// @@ -587,7 +662,7 @@ static LuminousIntensityUnit ParseUnit(string str, IFormatProvider formatProvide /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(LuminousIntensityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(LuminousIntensityUnit unit, [CanBeNull] Culture culture) + public string ToString( + LuminousIntensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(LuminousIntensityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + LuminousIntensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(LuminousIntensityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + LuminousIntensityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of LuminousIntensity /// - public static LuminousIntensity MaxValue - { - get - { - return new LuminousIntensity(double.MaxValue); - } - } + public static LuminousIntensity MaxValue => new LuminousIntensity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of LuminousIntensity /// - public static LuminousIntensity MinValue + public static LuminousIntensity MinValue => new LuminousIntensity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitCandela() { - get + if (Unit == LuminousIntensityUnit.Candela) { return _value; } + + switch (Unit) { - return new LuminousIntensity(double.MinValue); - } - } - } + case LuminousIntensityUnit.Candela: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(LuminousIntensityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs index 2ed9a0c4a7..e9bc649ed6 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct MagneticField : IComparable, IComparable #endif { /// - /// Base unit of MagneticField. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagneticFieldUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _teslas; + public MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public MagneticField() : this(0) + public MagneticField() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public MagneticField(double teslas) { - _teslas = Convert.ToDouble(teslas); + _value = Convert.ToDouble(teslas); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + MagneticField(double numericValue, MagneticFieldUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Tesla. + /// + /// Value assuming base unit Tesla. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MagneticField(long teslas) - { - _teslas = Convert.ToDouble(teslas); - } + MagneticField(long teslas) : this(Convert.ToDouble(teslas), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Tesla. + /// + /// Value assuming base unit Tesla. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MagneticField(decimal teslas) - { - _teslas = Convert.ToDouble(teslas); - } + MagneticField(decimal teslas) : this(Convert.ToDouble(teslas), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public MagneticField(double teslas) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MagneticFieldUnit BaseUnit - { - get { return MagneticFieldUnit.Tesla; } - } + public static MagneticFieldUnit BaseUnit => MagneticFieldUnit.Tesla; /// /// All units of measurement for the MagneticField quantity. /// public static MagneticFieldUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().ToArray(); - /// /// Get MagneticField in Teslas. /// - public double Teslas - { - get { return _teslas; } - } + public double Teslas => As(MagneticFieldUnit.Tesla); #endregion #region Static - public static MagneticField Zero - { - get { return new MagneticField(); } - } + public static MagneticField Zero => new MagneticField(0, BaseUnit); /// /// Get MagneticField from Teslas. @@ -152,17 +179,13 @@ public static MagneticField Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MagneticField FromTeslas(double teslas) - { - double value = (double) teslas; - return new MagneticField(value); - } #else public static MagneticField FromTeslas(QuantityValue teslas) +#endif { double value = (double) teslas; - return new MagneticField((value)); + return new MagneticField(value, MagneticFieldUnit.Tesla); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static MagneticField From(double value, MagneticFieldUnit fromUnit) public static MagneticField From(QuantityValue value, MagneticFieldUnit fromUnit) #endif { - switch (fromUnit) - { - case MagneticFieldUnit.Tesla: - return FromTeslas(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MagneticField((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static MagneticField From(QuantityValue value, MagneticFieldUnit fromUnit { return null; } - switch (fromUnit) - { - case MagneticFieldUnit.Tesla: - return FromTeslas(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MagneticField((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(MagneticFieldUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MagneticFieldUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MagneticFieldUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(MagneticFieldUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static MagneticField operator -(MagneticField right) { - return new MagneticField(-right._teslas); + return new MagneticField(-right.Value, right.Unit); } public static MagneticField operator +(MagneticField left, MagneticField right) { - return new MagneticField(left._teslas + right._teslas); + return new MagneticField(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static MagneticField operator -(MagneticField left, MagneticField right) { - return new MagneticField(left._teslas - right._teslas); + return new MagneticField(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static MagneticField operator *(double left, MagneticField right) { - return new MagneticField(left*right._teslas); + return new MagneticField(left * right.Value, right.Unit); } public static MagneticField operator *(MagneticField left, double right) { - return new MagneticField(left._teslas*(double)right); + return new MagneticField(left.Value * right, left.Unit); } public static MagneticField operator /(MagneticField left, double right) { - return new MagneticField(left._teslas/(double)right); + return new MagneticField(left.Value / right, left.Unit); } public static double operator /(MagneticField left, MagneticField right) { - return Convert.ToDouble(left._teslas/right._teslas); + return left.Teslas / right.Teslas; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(MagneticField other) { - return _teslas.CompareTo(other._teslas); + return AsBaseUnitTeslas().CompareTo(other.AsBaseUnitTeslas()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(MagneticField left, MagneticField right) { - return left._teslas <= right._teslas; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(MagneticField left, MagneticField right) { - return left._teslas >= right._teslas; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(MagneticField left, MagneticField right) { - return left._teslas < right._teslas; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(MagneticField left, MagneticField right) { - return left._teslas > right._teslas; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(MagneticField left, MagneticField right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._teslas == right._teslas; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(MagneticField left, MagneticField right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._teslas != right._teslas; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _teslas.Equals(((MagneticField) obj)._teslas); + return AsBaseUnitTeslas().Equals(((MagneticField) obj).AsBaseUnitTeslas()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(MagneticField other, MagneticField maxError) { - return Math.Abs(_teslas - other._teslas) <= maxError._teslas; + return Math.Abs(AsBaseUnitTeslas() - other.AsBaseUnitTeslas()) <= maxError.AsBaseUnitTeslas(); } public override int GetHashCode() { - return _teslas.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MagneticFieldUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitTeslas(); + switch (unit) { - case MagneticFieldUnit.Tesla: - return Teslas; + case MagneticFieldUnit.Tesla: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static MagneticField Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static MagneticField Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MagneticField Parse(string str, [CanBeNull] Culture culture) + public static MagneticField Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out MagneticField result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out MagneticField result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out MagneticField result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static MagneticFieldUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MagneticFieldUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static MagneticFieldUnit ParseUnit(string str, [CanBeNull] string culture /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static MagneticFieldUnit ParseUnit(string str, [CanBeNull] string culture #else public #endif - static MagneticFieldUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MagneticFieldUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MagneticFieldUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagneticFieldUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static MagneticFieldUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Tesla /// @@ -587,7 +662,7 @@ static MagneticFieldUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(MagneticFieldUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MagneticFieldUnit unit, [CanBeNull] Culture culture) + public string ToString( + MagneticFieldUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MagneticFieldUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MagneticFieldUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MagneticFieldUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MagneticFieldUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of MagneticField /// - public static MagneticField MaxValue - { - get - { - return new MagneticField(double.MaxValue); - } - } + public static MagneticField MaxValue => new MagneticField(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of MagneticField /// - public static MagneticField MinValue + public static MagneticField MinValue => new MagneticField(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitTeslas() { - get + if (Unit == MagneticFieldUnit.Tesla) { return _value; } + + switch (Unit) { - return new MagneticField(double.MinValue); - } - } - } + case MagneticFieldUnit.Tesla: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MagneticFieldUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs index 2e86e49aba..f9e1ae8166 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct MagneticFlux : IComparable, IComparable #endif { /// - /// Base unit of MagneticFlux. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagneticFluxUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _webers; + public MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public MagneticFlux() : this(0) + public MagneticFlux() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public MagneticFlux(double webers) { - _webers = Convert.ToDouble(webers); + _value = Convert.ToDouble(webers); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + MagneticFlux(double numericValue, MagneticFluxUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Weber. + /// + /// Value assuming base unit Weber. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MagneticFlux(long webers) - { - _webers = Convert.ToDouble(webers); - } + MagneticFlux(long webers) : this(Convert.ToDouble(webers), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Weber. + /// + /// Value assuming base unit Weber. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MagneticFlux(decimal webers) - { - _webers = Convert.ToDouble(webers); - } + MagneticFlux(decimal webers) : this(Convert.ToDouble(webers), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public MagneticFlux(double webers) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MagneticFluxUnit BaseUnit - { - get { return MagneticFluxUnit.Weber; } - } + public static MagneticFluxUnit BaseUnit => MagneticFluxUnit.Weber; /// /// All units of measurement for the MagneticFlux quantity. /// public static MagneticFluxUnit[] Units { get; } = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().ToArray(); - /// /// Get MagneticFlux in Webers. /// - public double Webers - { - get { return _webers; } - } + public double Webers => As(MagneticFluxUnit.Weber); #endregion #region Static - public static MagneticFlux Zero - { - get { return new MagneticFlux(); } - } + public static MagneticFlux Zero => new MagneticFlux(0, BaseUnit); /// /// Get MagneticFlux from Webers. @@ -152,17 +179,13 @@ public static MagneticFlux Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MagneticFlux FromWebers(double webers) - { - double value = (double) webers; - return new MagneticFlux(value); - } #else public static MagneticFlux FromWebers(QuantityValue webers) +#endif { double value = (double) webers; - return new MagneticFlux((value)); + return new MagneticFlux(value, MagneticFluxUnit.Weber); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static MagneticFlux From(double value, MagneticFluxUnit fromUnit) public static MagneticFlux From(QuantityValue value, MagneticFluxUnit fromUnit) #endif { - switch (fromUnit) - { - case MagneticFluxUnit.Weber: - return FromWebers(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MagneticFlux((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static MagneticFlux From(QuantityValue value, MagneticFluxUnit fromUnit) { return null; } - switch (fromUnit) - { - case MagneticFluxUnit.Weber: - return FromWebers(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MagneticFlux((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(MagneticFluxUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MagneticFluxUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MagneticFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(MagneticFluxUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static MagneticFlux operator -(MagneticFlux right) { - return new MagneticFlux(-right._webers); + return new MagneticFlux(-right.Value, right.Unit); } public static MagneticFlux operator +(MagneticFlux left, MagneticFlux right) { - return new MagneticFlux(left._webers + right._webers); + return new MagneticFlux(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static MagneticFlux operator -(MagneticFlux left, MagneticFlux right) { - return new MagneticFlux(left._webers - right._webers); + return new MagneticFlux(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static MagneticFlux operator *(double left, MagneticFlux right) { - return new MagneticFlux(left*right._webers); + return new MagneticFlux(left * right.Value, right.Unit); } public static MagneticFlux operator *(MagneticFlux left, double right) { - return new MagneticFlux(left._webers*(double)right); + return new MagneticFlux(left.Value * right, left.Unit); } public static MagneticFlux operator /(MagneticFlux left, double right) { - return new MagneticFlux(left._webers/(double)right); + return new MagneticFlux(left.Value / right, left.Unit); } public static double operator /(MagneticFlux left, MagneticFlux right) { - return Convert.ToDouble(left._webers/right._webers); + return left.Webers / right.Webers; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(MagneticFlux other) { - return _webers.CompareTo(other._webers); + return AsBaseUnitWebers().CompareTo(other.AsBaseUnitWebers()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(MagneticFlux left, MagneticFlux right) { - return left._webers <= right._webers; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(MagneticFlux left, MagneticFlux right) { - return left._webers >= right._webers; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(MagneticFlux left, MagneticFlux right) { - return left._webers < right._webers; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(MagneticFlux left, MagneticFlux right) { - return left._webers > right._webers; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(MagneticFlux left, MagneticFlux right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._webers == right._webers; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(MagneticFlux left, MagneticFlux right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._webers != right._webers; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _webers.Equals(((MagneticFlux) obj)._webers); + return AsBaseUnitWebers().Equals(((MagneticFlux) obj).AsBaseUnitWebers()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(MagneticFlux other, MagneticFlux maxError) { - return Math.Abs(_webers - other._webers) <= maxError._webers; + return Math.Abs(AsBaseUnitWebers() - other.AsBaseUnitWebers()) <= maxError.AsBaseUnitWebers(); } public override int GetHashCode() { - return _webers.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MagneticFluxUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitWebers(); + switch (unit) { - case MagneticFluxUnit.Weber: - return Webers; + case MagneticFluxUnit.Weber: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static MagneticFlux Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static MagneticFlux Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MagneticFlux Parse(string str, [CanBeNull] Culture culture) + public static MagneticFlux Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out MagneticFlux result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out MagneticFlux result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out MagneticFlux result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static MagneticFluxUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MagneticFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static MagneticFluxUnit ParseUnit(string str, [CanBeNull] string cultureN /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static MagneticFluxUnit ParseUnit(string str, [CanBeNull] string cultureN #else public #endif - static MagneticFluxUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MagneticFluxUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MagneticFluxUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagneticFluxUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static MagneticFluxUnit ParseUnit(string str, IFormatProvider formatProvider = n #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Weber /// @@ -587,7 +662,7 @@ static MagneticFluxUnit ParseUnit(string str, IFormatProvider formatProvider = n /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(MagneticFluxUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MagneticFluxUnit unit, [CanBeNull] Culture culture) + public string ToString( + MagneticFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MagneticFluxUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MagneticFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MagneticFluxUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MagneticFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of MagneticFlux /// - public static MagneticFlux MaxValue - { - get - { - return new MagneticFlux(double.MaxValue); - } - } + public static MagneticFlux MaxValue => new MagneticFlux(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of MagneticFlux /// - public static MagneticFlux MinValue + public static MagneticFlux MinValue => new MagneticFlux(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitWebers() { - get + if (Unit == MagneticFluxUnit.Weber) { return _value; } + + switch (Unit) { - return new MagneticFlux(double.MinValue); - } - } - } + case MagneticFluxUnit.Weber: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MagneticFluxUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs index e7e4a4cfe7..9383885bd7 100644 --- a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Magnetization : IComparable, IComparable #endif { /// - /// Base unit of Magnetization. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MagnetizationUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _amperesPerMeter; + public MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Magnetization() : this(0) + public Magnetization() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Magnetization(double amperespermeter) { - _amperesPerMeter = Convert.ToDouble(amperespermeter); + _value = Convert.ToDouble(amperespermeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Magnetization(double numericValue, MagnetizationUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit AmperePerMeter. + /// + /// Value assuming base unit AmperePerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Magnetization(long amperespermeter) - { - _amperesPerMeter = Convert.ToDouble(amperespermeter); - } + Magnetization(long amperespermeter) : this(Convert.ToDouble(amperespermeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit AmperePerMeter. + /// + /// Value assuming base unit AmperePerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Magnetization(decimal amperespermeter) - { - _amperesPerMeter = Convert.ToDouble(amperespermeter); - } + Magnetization(decimal amperespermeter) : this(Convert.ToDouble(amperespermeter), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public Magnetization(double amperespermeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MagnetizationUnit BaseUnit - { - get { return MagnetizationUnit.AmperePerMeter; } - } + public static MagnetizationUnit BaseUnit => MagnetizationUnit.AmperePerMeter; /// /// All units of measurement for the Magnetization quantity. /// public static MagnetizationUnit[] Units { get; } = Enum.GetValues(typeof(MagnetizationUnit)).Cast().ToArray(); - /// /// Get Magnetization in AmperesPerMeter. /// - public double AmperesPerMeter - { - get { return _amperesPerMeter; } - } + public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); #endregion #region Static - public static Magnetization Zero - { - get { return new Magnetization(); } - } + public static Magnetization Zero => new Magnetization(0, BaseUnit); /// /// Get Magnetization from AmperesPerMeter. @@ -152,17 +179,13 @@ public static Magnetization Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Magnetization FromAmperesPerMeter(double amperespermeter) - { - double value = (double) amperespermeter; - return new Magnetization(value); - } #else public static Magnetization FromAmperesPerMeter(QuantityValue amperespermeter) +#endif { double value = (double) amperespermeter; - return new Magnetization((value)); + return new Magnetization(value, MagnetizationUnit.AmperePerMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static Magnetization From(double value, MagnetizationUnit fromUnit) public static Magnetization From(QuantityValue value, MagnetizationUnit fromUnit) #endif { - switch (fromUnit) - { - case MagnetizationUnit.AmperePerMeter: - return FromAmperesPerMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Magnetization((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static Magnetization From(QuantityValue value, MagnetizationUnit fromUnit { return null; } - switch (fromUnit) - { - case MagnetizationUnit.AmperePerMeter: - return FromAmperesPerMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Magnetization((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(MagnetizationUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MagnetizationUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MagnetizationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(MagnetizationUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static Magnetization operator -(Magnetization right) { - return new Magnetization(-right._amperesPerMeter); + return new Magnetization(-right.Value, right.Unit); } public static Magnetization operator +(Magnetization left, Magnetization right) { - return new Magnetization(left._amperesPerMeter + right._amperesPerMeter); + return new Magnetization(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Magnetization operator -(Magnetization left, Magnetization right) { - return new Magnetization(left._amperesPerMeter - right._amperesPerMeter); + return new Magnetization(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Magnetization operator *(double left, Magnetization right) { - return new Magnetization(left*right._amperesPerMeter); + return new Magnetization(left * right.Value, right.Unit); } public static Magnetization operator *(Magnetization left, double right) { - return new Magnetization(left._amperesPerMeter*(double)right); + return new Magnetization(left.Value * right, left.Unit); } public static Magnetization operator /(Magnetization left, double right) { - return new Magnetization(left._amperesPerMeter/(double)right); + return new Magnetization(left.Value / right, left.Unit); } public static double operator /(Magnetization left, Magnetization right) { - return Convert.ToDouble(left._amperesPerMeter/right._amperesPerMeter); + return left.AmperesPerMeter / right.AmperesPerMeter; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(Magnetization other) { - return _amperesPerMeter.CompareTo(other._amperesPerMeter); + return AsBaseUnitAmperesPerMeter().CompareTo(other.AsBaseUnitAmperesPerMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Magnetization left, Magnetization right) { - return left._amperesPerMeter <= right._amperesPerMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Magnetization left, Magnetization right) { - return left._amperesPerMeter >= right._amperesPerMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Magnetization left, Magnetization right) { - return left._amperesPerMeter < right._amperesPerMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Magnetization left, Magnetization right) { - return left._amperesPerMeter > right._amperesPerMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Magnetization left, Magnetization right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._amperesPerMeter == right._amperesPerMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Magnetization left, Magnetization right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._amperesPerMeter != right._amperesPerMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _amperesPerMeter.Equals(((Magnetization) obj)._amperesPerMeter); + return AsBaseUnitAmperesPerMeter().Equals(((Magnetization) obj).AsBaseUnitAmperesPerMeter()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Magnetization other, Magnetization maxError) { - return Math.Abs(_amperesPerMeter - other._amperesPerMeter) <= maxError._amperesPerMeter; + return Math.Abs(AsBaseUnitAmperesPerMeter() - other.AsBaseUnitAmperesPerMeter()) <= maxError.AsBaseUnitAmperesPerMeter(); } public override int GetHashCode() { - return _amperesPerMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MagnetizationUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitAmperesPerMeter(); + switch (unit) { - case MagnetizationUnit.AmperePerMeter: - return AmperesPerMeter; + case MagnetizationUnit.AmperePerMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static Magnetization Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static Magnetization Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Magnetization Parse(string str, [CanBeNull] Culture culture) + public static Magnetization Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out Magnetization result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Magnetization result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Magnetization result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static MagnetizationUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MagnetizationUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static MagnetizationUnit ParseUnit(string str, [CanBeNull] string culture /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static MagnetizationUnit ParseUnit(string str, [CanBeNull] string culture #else public #endif - static MagnetizationUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MagnetizationUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MagnetizationUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MagnetizationUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static MagnetizationUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is AmperePerMeter /// @@ -587,7 +662,7 @@ static MagnetizationUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(MagnetizationUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MagnetizationUnit unit, [CanBeNull] Culture culture) + public string ToString( + MagnetizationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MagnetizationUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MagnetizationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MagnetizationUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MagnetizationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Magnetization /// - public static Magnetization MaxValue - { - get - { - return new Magnetization(double.MaxValue); - } - } + public static Magnetization MaxValue => new Magnetization(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Magnetization /// - public static Magnetization MinValue + public static Magnetization MinValue => new Magnetization(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitAmperesPerMeter() { - get + if (Unit == MagnetizationUnit.AmperePerMeter) { return _value; } + + switch (Unit) { - return new Magnetization(double.MinValue); - } - } - } + case MagnetizationUnit.AmperePerMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MagnetizationUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs index 80952b297f..c33dd4cd2b 100644 --- a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Mass : IComparable, IComparable #endif { /// - /// Base unit of Mass. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _kilograms; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Mass() : this(0) + public Mass() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Mass(double kilograms) { - _kilograms = Convert.ToDouble(kilograms); + _value = Convert.ToDouble(kilograms); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Mass(double numericValue, MassUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Kilogram. + /// + /// Value assuming base unit Kilogram. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Mass(long kilograms) - { - _kilograms = Convert.ToDouble(kilograms); - } + Mass(long kilograms) : this(Convert.ToDouble(kilograms), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Kilogram. + /// + /// Value assuming base unit Kilogram. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Mass(decimal kilograms) - { - _kilograms = Convert.ToDouble(kilograms); - } + Mass(decimal kilograms) : this(Convert.ToDouble(kilograms), BaseUnit) { } #region Properties @@ -119,192 +156,102 @@ public Mass(double kilograms) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MassUnit BaseUnit - { - get { return MassUnit.Kilogram; } - } + public static MassUnit BaseUnit => MassUnit.Kilogram; /// /// All units of measurement for the Mass quantity. /// public static MassUnit[] Units { get; } = Enum.GetValues(typeof(MassUnit)).Cast().ToArray(); - /// /// Get Mass in Centigrams. /// - public double Centigrams - { - get { return (_kilograms*1e3) / 1e-2d; } - } - + public double Centigrams => As(MassUnit.Centigram); /// /// Get Mass in Decagrams. /// - public double Decagrams - { - get { return (_kilograms*1e3) / 1e1d; } - } - + public double Decagrams => As(MassUnit.Decagram); /// /// Get Mass in Decigrams. /// - public double Decigrams - { - get { return (_kilograms*1e3) / 1e-1d; } - } - + public double Decigrams => As(MassUnit.Decigram); /// /// Get Mass in Grams. /// - public double Grams - { - get { return _kilograms*1e3; } - } - + public double Grams => As(MassUnit.Gram); /// /// Get Mass in Hectograms. /// - public double Hectograms - { - get { return (_kilograms*1e3) / 1e2d; } - } - + public double Hectograms => As(MassUnit.Hectogram); /// /// Get Mass in Kilograms. /// - public double Kilograms - { - get { return (_kilograms*1e3) / 1e3d; } - } - + public double Kilograms => As(MassUnit.Kilogram); /// /// Get Mass in Kilopounds. /// - public double Kilopounds - { - get { return (_kilograms/0.45359237) / 1e3d; } - } - + public double Kilopounds => As(MassUnit.Kilopound); /// /// Get Mass in Kilotonnes. /// - public double Kilotonnes - { - get { return (_kilograms/1e3) / 1e3d; } - } - + public double Kilotonnes => As(MassUnit.Kilotonne); /// /// Get Mass in LongHundredweight. /// - public double LongHundredweight - { - get { return _kilograms*0.01968413055222121; } - } - + public double LongHundredweight => As(MassUnit.LongHundredweight); /// /// Get Mass in LongTons. /// - public double LongTons - { - get { return _kilograms/1016.0469088; } - } - + public double LongTons => As(MassUnit.LongTon); /// /// Get Mass in Megapounds. /// - public double Megapounds - { - get { return (_kilograms/0.45359237) / 1e6d; } - } - + public double Megapounds => As(MassUnit.Megapound); /// /// Get Mass in Megatonnes. /// - public double Megatonnes - { - get { return (_kilograms/1e3) / 1e6d; } - } - + public double Megatonnes => As(MassUnit.Megatonne); /// /// Get Mass in Micrograms. /// - public double Micrograms - { - get { return (_kilograms*1e3) / 1e-6d; } - } - + public double Micrograms => As(MassUnit.Microgram); /// /// Get Mass in Milligrams. /// - public double Milligrams - { - get { return (_kilograms*1e3) / 1e-3d; } - } - + public double Milligrams => As(MassUnit.Milligram); /// /// Get Mass in Nanograms. /// - public double Nanograms - { - get { return (_kilograms*1e3) / 1e-9d; } - } - + public double Nanograms => As(MassUnit.Nanogram); /// /// Get Mass in Ounces. /// - public double Ounces - { - get { return _kilograms*35.2739619; } - } - + public double Ounces => As(MassUnit.Ounce); /// /// Get Mass in Pounds. /// - public double Pounds - { - get { return _kilograms/0.45359237; } - } - + public double Pounds => As(MassUnit.Pound); /// /// Get Mass in ShortHundredweight. /// - public double ShortHundredweight - { - get { return _kilograms*0.022046226218487758; } - } - + public double ShortHundredweight => As(MassUnit.ShortHundredweight); /// /// Get Mass in ShortTons. /// - public double ShortTons - { - get { return _kilograms/907.18474; } - } - + public double ShortTons => As(MassUnit.ShortTon); /// /// Get Mass in Stone. /// - public double Stone - { - get { return _kilograms*0.1574731728702698; } - } - + public double Stone => As(MassUnit.Stone); /// /// Get Mass in Tonnes. /// - public double Tonnes - { - get { return _kilograms/1e3; } - } + public double Tonnes => As(MassUnit.Tonne); #endregion #region Static - public static Mass Zero - { - get { return new Mass(); } - } + public static Mass Zero => new Mass(0, BaseUnit); /// /// Get Mass from Centigrams. @@ -312,17 +259,13 @@ public static Mass Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromCentigrams(double centigrams) - { - double value = (double) centigrams; - return new Mass((value/1e3) * 1e-2d); - } #else public static Mass FromCentigrams(QuantityValue centigrams) +#endif { double value = (double) centigrams; - return new Mass(((value/1e3) * 1e-2d)); + return new Mass(value, MassUnit.Centigram); } -#endif /// /// Get Mass from Decagrams. @@ -330,17 +273,13 @@ public static Mass FromCentigrams(QuantityValue centigrams) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromDecagrams(double decagrams) - { - double value = (double) decagrams; - return new Mass((value/1e3) * 1e1d); - } #else public static Mass FromDecagrams(QuantityValue decagrams) +#endif { double value = (double) decagrams; - return new Mass(((value/1e3) * 1e1d)); + return new Mass(value, MassUnit.Decagram); } -#endif /// /// Get Mass from Decigrams. @@ -348,17 +287,13 @@ public static Mass FromDecagrams(QuantityValue decagrams) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromDecigrams(double decigrams) - { - double value = (double) decigrams; - return new Mass((value/1e3) * 1e-1d); - } #else public static Mass FromDecigrams(QuantityValue decigrams) +#endif { double value = (double) decigrams; - return new Mass(((value/1e3) * 1e-1d)); + return new Mass(value, MassUnit.Decigram); } -#endif /// /// Get Mass from Grams. @@ -366,17 +301,13 @@ public static Mass FromDecigrams(QuantityValue decigrams) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromGrams(double grams) - { - double value = (double) grams; - return new Mass(value/1e3); - } #else public static Mass FromGrams(QuantityValue grams) +#endif { double value = (double) grams; - return new Mass((value/1e3)); + return new Mass(value, MassUnit.Gram); } -#endif /// /// Get Mass from Hectograms. @@ -384,17 +315,13 @@ public static Mass FromGrams(QuantityValue grams) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromHectograms(double hectograms) - { - double value = (double) hectograms; - return new Mass((value/1e3) * 1e2d); - } #else public static Mass FromHectograms(QuantityValue hectograms) +#endif { double value = (double) hectograms; - return new Mass(((value/1e3) * 1e2d)); + return new Mass(value, MassUnit.Hectogram); } -#endif /// /// Get Mass from Kilograms. @@ -402,17 +329,13 @@ public static Mass FromHectograms(QuantityValue hectograms) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromKilograms(double kilograms) - { - double value = (double) kilograms; - return new Mass((value/1e3) * 1e3d); - } #else public static Mass FromKilograms(QuantityValue kilograms) +#endif { double value = (double) kilograms; - return new Mass(((value/1e3) * 1e3d)); + return new Mass(value, MassUnit.Kilogram); } -#endif /// /// Get Mass from Kilopounds. @@ -420,17 +343,13 @@ public static Mass FromKilograms(QuantityValue kilograms) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromKilopounds(double kilopounds) - { - double value = (double) kilopounds; - return new Mass((value*0.45359237) * 1e3d); - } #else public static Mass FromKilopounds(QuantityValue kilopounds) +#endif { double value = (double) kilopounds; - return new Mass(((value*0.45359237) * 1e3d)); + return new Mass(value, MassUnit.Kilopound); } -#endif /// /// Get Mass from Kilotonnes. @@ -438,17 +357,13 @@ public static Mass FromKilopounds(QuantityValue kilopounds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromKilotonnes(double kilotonnes) - { - double value = (double) kilotonnes; - return new Mass((value*1e3) * 1e3d); - } #else public static Mass FromKilotonnes(QuantityValue kilotonnes) +#endif { double value = (double) kilotonnes; - return new Mass(((value*1e3) * 1e3d)); + return new Mass(value, MassUnit.Kilotonne); } -#endif /// /// Get Mass from LongHundredweight. @@ -456,17 +371,13 @@ public static Mass FromKilotonnes(QuantityValue kilotonnes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromLongHundredweight(double longhundredweight) - { - double value = (double) longhundredweight; - return new Mass(value/0.01968413055222121); - } #else public static Mass FromLongHundredweight(QuantityValue longhundredweight) +#endif { double value = (double) longhundredweight; - return new Mass((value/0.01968413055222121)); + return new Mass(value, MassUnit.LongHundredweight); } -#endif /// /// Get Mass from LongTons. @@ -474,17 +385,13 @@ public static Mass FromLongHundredweight(QuantityValue longhundredweight) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromLongTons(double longtons) - { - double value = (double) longtons; - return new Mass(value*1016.0469088); - } #else public static Mass FromLongTons(QuantityValue longtons) +#endif { double value = (double) longtons; - return new Mass((value*1016.0469088)); + return new Mass(value, MassUnit.LongTon); } -#endif /// /// Get Mass from Megapounds. @@ -492,17 +399,13 @@ public static Mass FromLongTons(QuantityValue longtons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromMegapounds(double megapounds) - { - double value = (double) megapounds; - return new Mass((value*0.45359237) * 1e6d); - } #else public static Mass FromMegapounds(QuantityValue megapounds) +#endif { double value = (double) megapounds; - return new Mass(((value*0.45359237) * 1e6d)); + return new Mass(value, MassUnit.Megapound); } -#endif /// /// Get Mass from Megatonnes. @@ -510,17 +413,13 @@ public static Mass FromMegapounds(QuantityValue megapounds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromMegatonnes(double megatonnes) - { - double value = (double) megatonnes; - return new Mass((value*1e3) * 1e6d); - } #else public static Mass FromMegatonnes(QuantityValue megatonnes) +#endif { double value = (double) megatonnes; - return new Mass(((value*1e3) * 1e6d)); + return new Mass(value, MassUnit.Megatonne); } -#endif /// /// Get Mass from Micrograms. @@ -528,17 +427,13 @@ public static Mass FromMegatonnes(QuantityValue megatonnes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromMicrograms(double micrograms) - { - double value = (double) micrograms; - return new Mass((value/1e3) * 1e-6d); - } #else public static Mass FromMicrograms(QuantityValue micrograms) +#endif { double value = (double) micrograms; - return new Mass(((value/1e3) * 1e-6d)); + return new Mass(value, MassUnit.Microgram); } -#endif /// /// Get Mass from Milligrams. @@ -546,17 +441,13 @@ public static Mass FromMicrograms(QuantityValue micrograms) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromMilligrams(double milligrams) - { - double value = (double) milligrams; - return new Mass((value/1e3) * 1e-3d); - } #else public static Mass FromMilligrams(QuantityValue milligrams) +#endif { double value = (double) milligrams; - return new Mass(((value/1e3) * 1e-3d)); + return new Mass(value, MassUnit.Milligram); } -#endif /// /// Get Mass from Nanograms. @@ -564,17 +455,13 @@ public static Mass FromMilligrams(QuantityValue milligrams) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromNanograms(double nanograms) - { - double value = (double) nanograms; - return new Mass((value/1e3) * 1e-9d); - } #else public static Mass FromNanograms(QuantityValue nanograms) +#endif { double value = (double) nanograms; - return new Mass(((value/1e3) * 1e-9d)); + return new Mass(value, MassUnit.Nanogram); } -#endif /// /// Get Mass from Ounces. @@ -582,17 +469,13 @@ public static Mass FromNanograms(QuantityValue nanograms) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromOunces(double ounces) - { - double value = (double) ounces; - return new Mass(value/35.2739619); - } #else public static Mass FromOunces(QuantityValue ounces) +#endif { double value = (double) ounces; - return new Mass((value/35.2739619)); + return new Mass(value, MassUnit.Ounce); } -#endif /// /// Get Mass from Pounds. @@ -600,17 +483,13 @@ public static Mass FromOunces(QuantityValue ounces) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromPounds(double pounds) - { - double value = (double) pounds; - return new Mass(value*0.45359237); - } #else public static Mass FromPounds(QuantityValue pounds) +#endif { double value = (double) pounds; - return new Mass((value*0.45359237)); + return new Mass(value, MassUnit.Pound); } -#endif /// /// Get Mass from ShortHundredweight. @@ -618,17 +497,13 @@ public static Mass FromPounds(QuantityValue pounds) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromShortHundredweight(double shorthundredweight) - { - double value = (double) shorthundredweight; - return new Mass(value/0.022046226218487758); - } #else public static Mass FromShortHundredweight(QuantityValue shorthundredweight) +#endif { double value = (double) shorthundredweight; - return new Mass((value/0.022046226218487758)); + return new Mass(value, MassUnit.ShortHundredweight); } -#endif /// /// Get Mass from ShortTons. @@ -636,17 +511,13 @@ public static Mass FromShortHundredweight(QuantityValue shorthundredweight) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromShortTons(double shorttons) - { - double value = (double) shorttons; - return new Mass(value*907.18474); - } #else public static Mass FromShortTons(QuantityValue shorttons) +#endif { double value = (double) shorttons; - return new Mass((value*907.18474)); + return new Mass(value, MassUnit.ShortTon); } -#endif /// /// Get Mass from Stone. @@ -654,17 +525,13 @@ public static Mass FromShortTons(QuantityValue shorttons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromStone(double stone) - { - double value = (double) stone; - return new Mass(value/0.1574731728702698); - } #else public static Mass FromStone(QuantityValue stone) +#endif { double value = (double) stone; - return new Mass((value/0.1574731728702698)); + return new Mass(value, MassUnit.Stone); } -#endif /// /// Get Mass from Tonnes. @@ -672,17 +539,13 @@ public static Mass FromStone(QuantityValue stone) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Mass FromTonnes(double tonnes) - { - double value = (double) tonnes; - return new Mass(value*1e3); - } #else public static Mass FromTonnes(QuantityValue tonnes) +#endif { double value = (double) tonnes; - return new Mass((value*1e3)); + return new Mass(value, MassUnit.Tonne); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1017,54 +880,7 @@ public static Mass From(double value, MassUnit fromUnit) public static Mass From(QuantityValue value, MassUnit fromUnit) #endif { - switch (fromUnit) - { - case MassUnit.Centigram: - return FromCentigrams(value); - case MassUnit.Decagram: - return FromDecagrams(value); - case MassUnit.Decigram: - return FromDecigrams(value); - case MassUnit.Gram: - return FromGrams(value); - case MassUnit.Hectogram: - return FromHectograms(value); - case MassUnit.Kilogram: - return FromKilograms(value); - case MassUnit.Kilopound: - return FromKilopounds(value); - case MassUnit.Kilotonne: - return FromKilotonnes(value); - case MassUnit.LongHundredweight: - return FromLongHundredweight(value); - case MassUnit.LongTon: - return FromLongTons(value); - case MassUnit.Megapound: - return FromMegapounds(value); - case MassUnit.Megatonne: - return FromMegatonnes(value); - case MassUnit.Microgram: - return FromMicrograms(value); - case MassUnit.Milligram: - return FromMilligrams(value); - case MassUnit.Nanogram: - return FromNanograms(value); - case MassUnit.Ounce: - return FromOunces(value); - case MassUnit.Pound: - return FromPounds(value); - case MassUnit.ShortHundredweight: - return FromShortHundredweight(value); - case MassUnit.ShortTon: - return FromShortTons(value); - case MassUnit.Stone: - return FromStone(value); - case MassUnit.Tonne: - return FromTonnes(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Mass((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1081,54 +897,8 @@ public static Mass From(QuantityValue value, MassUnit fromUnit) { return null; } - switch (fromUnit) - { - case MassUnit.Centigram: - return FromCentigrams(value.Value); - case MassUnit.Decagram: - return FromDecagrams(value.Value); - case MassUnit.Decigram: - return FromDecigrams(value.Value); - case MassUnit.Gram: - return FromGrams(value.Value); - case MassUnit.Hectogram: - return FromHectograms(value.Value); - case MassUnit.Kilogram: - return FromKilograms(value.Value); - case MassUnit.Kilopound: - return FromKilopounds(value.Value); - case MassUnit.Kilotonne: - return FromKilotonnes(value.Value); - case MassUnit.LongHundredweight: - return FromLongHundredweight(value.Value); - case MassUnit.LongTon: - return FromLongTons(value.Value); - case MassUnit.Megapound: - return FromMegapounds(value.Value); - case MassUnit.Megatonne: - return FromMegatonnes(value.Value); - case MassUnit.Microgram: - return FromMicrograms(value.Value); - case MassUnit.Milligram: - return FromMilligrams(value.Value); - case MassUnit.Nanogram: - return FromNanograms(value.Value); - case MassUnit.Ounce: - return FromOunces(value.Value); - case MassUnit.Pound: - return FromPounds(value.Value); - case MassUnit.ShortHundredweight: - return FromShortHundredweight(value.Value); - case MassUnit.ShortTon: - return FromShortTons(value.Value); - case MassUnit.Stone: - return FromStone(value.Value); - case MassUnit.Tonne: - return FromTonnes(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Mass((double)value.Value, fromUnit); } #endif @@ -1147,12 +917,29 @@ public static string GetAbbreviation(MassUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MassUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MassUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1163,37 +950,37 @@ public static string GetAbbreviation(MassUnit unit, [CanBeNull] Culture culture) #if !WINDOWS_UWP public static Mass operator -(Mass right) { - return new Mass(-right._kilograms); + return new Mass(-right.Value, right.Unit); } public static Mass operator +(Mass left, Mass right) { - return new Mass(left._kilograms + right._kilograms); + return new Mass(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Mass operator -(Mass left, Mass right) { - return new Mass(left._kilograms - right._kilograms); + return new Mass(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Mass operator *(double left, Mass right) { - return new Mass(left*right._kilograms); + return new Mass(left * right.Value, right.Unit); } public static Mass operator *(Mass left, double right) { - return new Mass(left._kilograms*(double)right); + return new Mass(left.Value * right, left.Unit); } public static Mass operator /(Mass left, double right) { - return new Mass(left._kilograms/(double)right); + return new Mass(left.Value / right, left.Unit); } public static double operator /(Mass left, Mass right) { - return Convert.ToDouble(left._kilograms/right._kilograms); + return left.Kilograms / right.Kilograms; } #endif @@ -1216,43 +1003,43 @@ public int CompareTo(object obj) #endif int CompareTo(Mass other) { - return _kilograms.CompareTo(other._kilograms); + return AsBaseUnitKilograms().CompareTo(other.AsBaseUnitKilograms()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Mass left, Mass right) { - return left._kilograms <= right._kilograms; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Mass left, Mass right) { - return left._kilograms >= right._kilograms; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Mass left, Mass right) { - return left._kilograms < right._kilograms; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Mass left, Mass right) { - return left._kilograms > right._kilograms; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Mass left, Mass right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilograms == right._kilograms; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Mass left, Mass right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilograms != right._kilograms; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1264,7 +1051,7 @@ public override bool Equals(object obj) return false; } - return _kilograms.Equals(((Mass) obj)._kilograms); + return AsBaseUnitKilograms().Equals(((Mass) obj).AsBaseUnitKilograms()); } /// @@ -1277,12 +1064,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Mass other, Mass maxError) { - return Math.Abs(_kilograms - other._kilograms) <= maxError._kilograms; + return Math.Abs(AsBaseUnitKilograms() - other.AsBaseUnitKilograms()) <= maxError.AsBaseUnitKilograms(); } public override int GetHashCode() { - return _kilograms.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1292,54 +1079,39 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MassUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitKilograms(); + switch (unit) { - case MassUnit.Centigram: - return Centigrams; - case MassUnit.Decagram: - return Decagrams; - case MassUnit.Decigram: - return Decigrams; - case MassUnit.Gram: - return Grams; - case MassUnit.Hectogram: - return Hectograms; - case MassUnit.Kilogram: - return Kilograms; - case MassUnit.Kilopound: - return Kilopounds; - case MassUnit.Kilotonne: - return Kilotonnes; - case MassUnit.LongHundredweight: - return LongHundredweight; - case MassUnit.LongTon: - return LongTons; - case MassUnit.Megapound: - return Megapounds; - case MassUnit.Megatonne: - return Megatonnes; - case MassUnit.Microgram: - return Micrograms; - case MassUnit.Milligram: - return Milligrams; - case MassUnit.Nanogram: - return Nanograms; - case MassUnit.Ounce: - return Ounces; - case MassUnit.Pound: - return Pounds; - case MassUnit.ShortHundredweight: - return ShortHundredweight; - case MassUnit.ShortTon: - return ShortTons; - case MassUnit.Stone: - return Stone; - case MassUnit.Tonne: - return Tonnes; + case MassUnit.Centigram: return (baseUnitValue*1e3) / 1e-2d; + case MassUnit.Decagram: return (baseUnitValue*1e3) / 1e1d; + case MassUnit.Decigram: return (baseUnitValue*1e3) / 1e-1d; + case MassUnit.Gram: return baseUnitValue*1e3; + case MassUnit.Hectogram: return (baseUnitValue*1e3) / 1e2d; + case MassUnit.Kilogram: return (baseUnitValue*1e3) / 1e3d; + case MassUnit.Kilopound: return (baseUnitValue/0.45359237) / 1e3d; + case MassUnit.Kilotonne: return (baseUnitValue/1e3) / 1e3d; + case MassUnit.LongHundredweight: return baseUnitValue*0.01968413055222121; + case MassUnit.LongTon: return baseUnitValue/1016.0469088; + case MassUnit.Megapound: return (baseUnitValue/0.45359237) / 1e6d; + case MassUnit.Megatonne: return (baseUnitValue/1e3) / 1e6d; + case MassUnit.Microgram: return (baseUnitValue*1e3) / 1e-6d; + case MassUnit.Milligram: return (baseUnitValue*1e3) / 1e-3d; + case MassUnit.Nanogram: return (baseUnitValue*1e3) / 1e-9d; + case MassUnit.Ounce: return baseUnitValue*35.2739619; + case MassUnit.Pound: return baseUnitValue/0.45359237; + case MassUnit.ShortHundredweight: return baseUnitValue*0.022046226218487758; + case MassUnit.ShortTon: return baseUnitValue/907.18474; + case MassUnit.Stone: return baseUnitValue*0.1574731728702698; + case MassUnit.Tonne: return baseUnitValue/1e3; default: throw new NotImplementedException("unit: " + unit); @@ -1381,7 +1153,11 @@ public static Mass Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1400,17 +1176,24 @@ public static Mass Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Mass Parse(string str, [CanBeNull] Culture culture) + public static Mass Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1436,16 +1219,41 @@ public static bool TryParse([CanBeNull] string str, out Mass result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Mass result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Mass result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1458,6 +1266,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1471,11 +1280,14 @@ public static MassUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MassUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1484,6 +1296,8 @@ public static MassUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1496,18 +1310,18 @@ public static MassUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static MassUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MassUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MassUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1516,6 +1330,7 @@ static MassUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Kilogram /// @@ -1527,7 +1342,7 @@ static MassUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1544,74 +1359,149 @@ public string ToString(MassUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MassUnit unit, [CanBeNull] Culture culture) + public string ToString( + MassUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MassUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MassUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MassUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MassUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Mass /// - public static Mass MaxValue - { - get - { - return new Mass(double.MaxValue); - } - } + public static Mass MaxValue => new Mass(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Mass /// - public static Mass MinValue + public static Mass MinValue => new Mass(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitKilograms() { - get + if (Unit == MassUnit.Kilogram) { return _value; } + + switch (Unit) { - return new Mass(double.MinValue); - } - } - } + case MassUnit.Centigram: return (_value/1e3) * 1e-2d; + case MassUnit.Decagram: return (_value/1e3) * 1e1d; + case MassUnit.Decigram: return (_value/1e3) * 1e-1d; + case MassUnit.Gram: return _value/1e3; + case MassUnit.Hectogram: return (_value/1e3) * 1e2d; + case MassUnit.Kilogram: return (_value/1e3) * 1e3d; + case MassUnit.Kilopound: return (_value*0.45359237) * 1e3d; + case MassUnit.Kilotonne: return (_value*1e3) * 1e3d; + case MassUnit.LongHundredweight: return _value/0.01968413055222121; + case MassUnit.LongTon: return _value*1016.0469088; + case MassUnit.Megapound: return (_value*0.45359237) * 1e6d; + case MassUnit.Megatonne: return (_value*1e3) * 1e6d; + case MassUnit.Microgram: return (_value/1e3) * 1e-6d; + case MassUnit.Milligram: return (_value/1e3) * 1e-3d; + case MassUnit.Nanogram: return (_value/1e3) * 1e-9d; + case MassUnit.Ounce: return _value/35.2739619; + case MassUnit.Pound: return _value*0.45359237; + case MassUnit.ShortHundredweight: return _value/0.022046226218487758; + case MassUnit.ShortTon: return _value*907.18474; + case MassUnit.Stone: return _value/0.1574731728702698; + case MassUnit.Tonne: return _value*1e3; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MassUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs index ff5afe075f..6e16facebe 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct MassFlow : IComparable, IComparable #endif { /// - /// Base unit of MassFlow. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassFlowUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _gramsPerSecond; + public MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public MassFlow() : this(0) + public MassFlow() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public MassFlow(double gramspersecond) { - _gramsPerSecond = Convert.ToDouble(gramspersecond); + _value = Convert.ToDouble(gramspersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + MassFlow(double numericValue, MassFlowUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit GramPerSecond. + /// + /// Value assuming base unit GramPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MassFlow(long gramspersecond) - { - _gramsPerSecond = Convert.ToDouble(gramspersecond); - } + MassFlow(long gramspersecond) : this(Convert.ToDouble(gramspersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit GramPerSecond. + /// + /// Value assuming base unit GramPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MassFlow(decimal gramspersecond) - { - _gramsPerSecond = Convert.ToDouble(gramspersecond); - } + MassFlow(decimal gramspersecond) : this(Convert.ToDouble(gramspersecond), BaseUnit) { } #region Properties @@ -119,144 +156,78 @@ public MassFlow(double gramspersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MassFlowUnit BaseUnit - { - get { return MassFlowUnit.GramPerSecond; } - } + public static MassFlowUnit BaseUnit => MassFlowUnit.GramPerSecond; /// /// All units of measurement for the MassFlow quantity. /// public static MassFlowUnit[] Units { get; } = Enum.GetValues(typeof(MassFlowUnit)).Cast().ToArray(); - /// /// Get MassFlow in CentigramsPerSecond. /// - public double CentigramsPerSecond - { - get { return (_gramsPerSecond) / 1e-2d; } - } - + public double CentigramsPerSecond => As(MassFlowUnit.CentigramPerSecond); /// /// Get MassFlow in DecagramsPerSecond. /// - public double DecagramsPerSecond - { - get { return (_gramsPerSecond) / 1e1d; } - } - + public double DecagramsPerSecond => As(MassFlowUnit.DecagramPerSecond); /// /// Get MassFlow in DecigramsPerSecond. /// - public double DecigramsPerSecond - { - get { return (_gramsPerSecond) / 1e-1d; } - } - + public double DecigramsPerSecond => As(MassFlowUnit.DecigramPerSecond); /// /// Get MassFlow in GramsPerSecond. /// - public double GramsPerSecond - { - get { return _gramsPerSecond; } - } - + public double GramsPerSecond => As(MassFlowUnit.GramPerSecond); /// /// Get MassFlow in HectogramsPerSecond. /// - public double HectogramsPerSecond - { - get { return (_gramsPerSecond) / 1e2d; } - } - + public double HectogramsPerSecond => As(MassFlowUnit.HectogramPerSecond); /// /// Get MassFlow in KilogramsPerHour. /// - public double KilogramsPerHour - { - get { return _gramsPerSecond*3.6; } - } - + public double KilogramsPerHour => As(MassFlowUnit.KilogramPerHour); /// /// Get MassFlow in KilogramsPerSecond. /// - public double KilogramsPerSecond - { - get { return (_gramsPerSecond) / 1e3d; } - } - + public double KilogramsPerSecond => As(MassFlowUnit.KilogramPerSecond); /// /// Get MassFlow in MegapoundsPerHour. /// - public double MegapoundsPerHour - { - get { return (_gramsPerSecond*7.93664) / 1e6d; } - } - + public double MegapoundsPerHour => As(MassFlowUnit.MegapoundPerHour); /// /// Get MassFlow in MicrogramsPerSecond. /// - public double MicrogramsPerSecond - { - get { return (_gramsPerSecond) / 1e-6d; } - } - + public double MicrogramsPerSecond => As(MassFlowUnit.MicrogramPerSecond); /// /// Get MassFlow in MilligramsPerSecond. /// - public double MilligramsPerSecond - { - get { return (_gramsPerSecond) / 1e-3d; } - } - + public double MilligramsPerSecond => As(MassFlowUnit.MilligramPerSecond); /// /// Get MassFlow in NanogramsPerSecond. /// - public double NanogramsPerSecond - { - get { return (_gramsPerSecond) / 1e-9d; } - } - + public double NanogramsPerSecond => As(MassFlowUnit.NanogramPerSecond); /// /// Get MassFlow in PoundsPerHour. /// - public double PoundsPerHour - { - get { return _gramsPerSecond*7.93664; } - } - + public double PoundsPerHour => As(MassFlowUnit.PoundPerHour); /// /// Get MassFlow in ShortTonsPerHour. /// - public double ShortTonsPerHour - { - get { return _gramsPerSecond/251.9957611; } - } - + public double ShortTonsPerHour => As(MassFlowUnit.ShortTonPerHour); /// /// Get MassFlow in TonnesPerDay. /// - public double TonnesPerDay - { - get { return _gramsPerSecond*0.0864000; } - } - + public double TonnesPerDay => As(MassFlowUnit.TonnePerDay); /// /// Get MassFlow in TonnesPerHour. /// - public double TonnesPerHour - { - get { return _gramsPerSecond*3.6/1000; } - } + public double TonnesPerHour => As(MassFlowUnit.TonnePerHour); #endregion #region Static - public static MassFlow Zero - { - get { return new MassFlow(); } - } + public static MassFlow Zero => new MassFlow(0, BaseUnit); /// /// Get MassFlow from CentigramsPerSecond. @@ -264,17 +235,13 @@ public static MassFlow Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromCentigramsPerSecond(double centigramspersecond) - { - double value = (double) centigramspersecond; - return new MassFlow((value) * 1e-2d); - } #else public static MassFlow FromCentigramsPerSecond(QuantityValue centigramspersecond) +#endif { double value = (double) centigramspersecond; - return new MassFlow(((value) * 1e-2d)); + return new MassFlow(value, MassFlowUnit.CentigramPerSecond); } -#endif /// /// Get MassFlow from DecagramsPerSecond. @@ -282,17 +249,13 @@ public static MassFlow FromCentigramsPerSecond(QuantityValue centigramspersecond #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromDecagramsPerSecond(double decagramspersecond) - { - double value = (double) decagramspersecond; - return new MassFlow((value) * 1e1d); - } #else public static MassFlow FromDecagramsPerSecond(QuantityValue decagramspersecond) +#endif { double value = (double) decagramspersecond; - return new MassFlow(((value) * 1e1d)); + return new MassFlow(value, MassFlowUnit.DecagramPerSecond); } -#endif /// /// Get MassFlow from DecigramsPerSecond. @@ -300,17 +263,13 @@ public static MassFlow FromDecagramsPerSecond(QuantityValue decagramspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromDecigramsPerSecond(double decigramspersecond) - { - double value = (double) decigramspersecond; - return new MassFlow((value) * 1e-1d); - } #else public static MassFlow FromDecigramsPerSecond(QuantityValue decigramspersecond) +#endif { double value = (double) decigramspersecond; - return new MassFlow(((value) * 1e-1d)); + return new MassFlow(value, MassFlowUnit.DecigramPerSecond); } -#endif /// /// Get MassFlow from GramsPerSecond. @@ -318,17 +277,13 @@ public static MassFlow FromDecigramsPerSecond(QuantityValue decigramspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromGramsPerSecond(double gramspersecond) - { - double value = (double) gramspersecond; - return new MassFlow(value); - } #else public static MassFlow FromGramsPerSecond(QuantityValue gramspersecond) +#endif { double value = (double) gramspersecond; - return new MassFlow((value)); + return new MassFlow(value, MassFlowUnit.GramPerSecond); } -#endif /// /// Get MassFlow from HectogramsPerSecond. @@ -336,17 +291,13 @@ public static MassFlow FromGramsPerSecond(QuantityValue gramspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromHectogramsPerSecond(double hectogramspersecond) - { - double value = (double) hectogramspersecond; - return new MassFlow((value) * 1e2d); - } #else public static MassFlow FromHectogramsPerSecond(QuantityValue hectogramspersecond) +#endif { double value = (double) hectogramspersecond; - return new MassFlow(((value) * 1e2d)); + return new MassFlow(value, MassFlowUnit.HectogramPerSecond); } -#endif /// /// Get MassFlow from KilogramsPerHour. @@ -354,17 +305,13 @@ public static MassFlow FromHectogramsPerSecond(QuantityValue hectogramspersecond #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromKilogramsPerHour(double kilogramsperhour) - { - double value = (double) kilogramsperhour; - return new MassFlow(value/3.6); - } #else public static MassFlow FromKilogramsPerHour(QuantityValue kilogramsperhour) +#endif { double value = (double) kilogramsperhour; - return new MassFlow((value/3.6)); + return new MassFlow(value, MassFlowUnit.KilogramPerHour); } -#endif /// /// Get MassFlow from KilogramsPerSecond. @@ -372,17 +319,13 @@ public static MassFlow FromKilogramsPerHour(QuantityValue kilogramsperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromKilogramsPerSecond(double kilogramspersecond) - { - double value = (double) kilogramspersecond; - return new MassFlow((value) * 1e3d); - } #else public static MassFlow FromKilogramsPerSecond(QuantityValue kilogramspersecond) +#endif { double value = (double) kilogramspersecond; - return new MassFlow(((value) * 1e3d)); + return new MassFlow(value, MassFlowUnit.KilogramPerSecond); } -#endif /// /// Get MassFlow from MegapoundsPerHour. @@ -390,17 +333,13 @@ public static MassFlow FromKilogramsPerSecond(QuantityValue kilogramspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromMegapoundsPerHour(double megapoundsperhour) - { - double value = (double) megapoundsperhour; - return new MassFlow((value/7.93664) * 1e6d); - } #else public static MassFlow FromMegapoundsPerHour(QuantityValue megapoundsperhour) +#endif { double value = (double) megapoundsperhour; - return new MassFlow(((value/7.93664) * 1e6d)); + return new MassFlow(value, MassFlowUnit.MegapoundPerHour); } -#endif /// /// Get MassFlow from MicrogramsPerSecond. @@ -408,17 +347,13 @@ public static MassFlow FromMegapoundsPerHour(QuantityValue megapoundsperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromMicrogramsPerSecond(double microgramspersecond) - { - double value = (double) microgramspersecond; - return new MassFlow((value) * 1e-6d); - } #else public static MassFlow FromMicrogramsPerSecond(QuantityValue microgramspersecond) +#endif { double value = (double) microgramspersecond; - return new MassFlow(((value) * 1e-6d)); + return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); } -#endif /// /// Get MassFlow from MilligramsPerSecond. @@ -426,17 +361,13 @@ public static MassFlow FromMicrogramsPerSecond(QuantityValue microgramspersecond #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromMilligramsPerSecond(double milligramspersecond) - { - double value = (double) milligramspersecond; - return new MassFlow((value) * 1e-3d); - } #else public static MassFlow FromMilligramsPerSecond(QuantityValue milligramspersecond) +#endif { double value = (double) milligramspersecond; - return new MassFlow(((value) * 1e-3d)); + return new MassFlow(value, MassFlowUnit.MilligramPerSecond); } -#endif /// /// Get MassFlow from NanogramsPerSecond. @@ -444,17 +375,13 @@ public static MassFlow FromMilligramsPerSecond(QuantityValue milligramspersecond #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromNanogramsPerSecond(double nanogramspersecond) - { - double value = (double) nanogramspersecond; - return new MassFlow((value) * 1e-9d); - } #else public static MassFlow FromNanogramsPerSecond(QuantityValue nanogramspersecond) +#endif { double value = (double) nanogramspersecond; - return new MassFlow(((value) * 1e-9d)); + return new MassFlow(value, MassFlowUnit.NanogramPerSecond); } -#endif /// /// Get MassFlow from PoundsPerHour. @@ -462,17 +389,13 @@ public static MassFlow FromNanogramsPerSecond(QuantityValue nanogramspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromPoundsPerHour(double poundsperhour) - { - double value = (double) poundsperhour; - return new MassFlow(value/7.93664); - } #else public static MassFlow FromPoundsPerHour(QuantityValue poundsperhour) +#endif { double value = (double) poundsperhour; - return new MassFlow((value/7.93664)); + return new MassFlow(value, MassFlowUnit.PoundPerHour); } -#endif /// /// Get MassFlow from ShortTonsPerHour. @@ -480,17 +403,13 @@ public static MassFlow FromPoundsPerHour(QuantityValue poundsperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromShortTonsPerHour(double shorttonsperhour) - { - double value = (double) shorttonsperhour; - return new MassFlow(value*251.9957611); - } #else public static MassFlow FromShortTonsPerHour(QuantityValue shorttonsperhour) +#endif { double value = (double) shorttonsperhour; - return new MassFlow((value*251.9957611)); + return new MassFlow(value, MassFlowUnit.ShortTonPerHour); } -#endif /// /// Get MassFlow from TonnesPerDay. @@ -498,17 +417,13 @@ public static MassFlow FromShortTonsPerHour(QuantityValue shorttonsperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromTonnesPerDay(double tonnesperday) - { - double value = (double) tonnesperday; - return new MassFlow(value/0.0864000); - } #else public static MassFlow FromTonnesPerDay(QuantityValue tonnesperday) +#endif { double value = (double) tonnesperday; - return new MassFlow((value/0.0864000)); + return new MassFlow(value, MassFlowUnit.TonnePerDay); } -#endif /// /// Get MassFlow from TonnesPerHour. @@ -516,17 +431,13 @@ public static MassFlow FromTonnesPerDay(QuantityValue tonnesperday) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlow FromTonnesPerHour(double tonnesperhour) - { - double value = (double) tonnesperhour; - return new MassFlow(1000*value/3.6); - } #else public static MassFlow FromTonnesPerHour(QuantityValue tonnesperhour) +#endif { double value = (double) tonnesperhour; - return new MassFlow((1000*value/3.6)); + return new MassFlow(value, MassFlowUnit.TonnePerHour); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -771,42 +682,7 @@ public static MassFlow From(double value, MassFlowUnit fromUnit) public static MassFlow From(QuantityValue value, MassFlowUnit fromUnit) #endif { - switch (fromUnit) - { - case MassFlowUnit.CentigramPerSecond: - return FromCentigramsPerSecond(value); - case MassFlowUnit.DecagramPerSecond: - return FromDecagramsPerSecond(value); - case MassFlowUnit.DecigramPerSecond: - return FromDecigramsPerSecond(value); - case MassFlowUnit.GramPerSecond: - return FromGramsPerSecond(value); - case MassFlowUnit.HectogramPerSecond: - return FromHectogramsPerSecond(value); - case MassFlowUnit.KilogramPerHour: - return FromKilogramsPerHour(value); - case MassFlowUnit.KilogramPerSecond: - return FromKilogramsPerSecond(value); - case MassFlowUnit.MegapoundPerHour: - return FromMegapoundsPerHour(value); - case MassFlowUnit.MicrogramPerSecond: - return FromMicrogramsPerSecond(value); - case MassFlowUnit.MilligramPerSecond: - return FromMilligramsPerSecond(value); - case MassFlowUnit.NanogramPerSecond: - return FromNanogramsPerSecond(value); - case MassFlowUnit.PoundPerHour: - return FromPoundsPerHour(value); - case MassFlowUnit.ShortTonPerHour: - return FromShortTonsPerHour(value); - case MassFlowUnit.TonnePerDay: - return FromTonnesPerDay(value); - case MassFlowUnit.TonnePerHour: - return FromTonnesPerHour(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MassFlow((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -823,42 +699,8 @@ public static MassFlow From(QuantityValue value, MassFlowUnit fromUnit) { return null; } - switch (fromUnit) - { - case MassFlowUnit.CentigramPerSecond: - return FromCentigramsPerSecond(value.Value); - case MassFlowUnit.DecagramPerSecond: - return FromDecagramsPerSecond(value.Value); - case MassFlowUnit.DecigramPerSecond: - return FromDecigramsPerSecond(value.Value); - case MassFlowUnit.GramPerSecond: - return FromGramsPerSecond(value.Value); - case MassFlowUnit.HectogramPerSecond: - return FromHectogramsPerSecond(value.Value); - case MassFlowUnit.KilogramPerHour: - return FromKilogramsPerHour(value.Value); - case MassFlowUnit.KilogramPerSecond: - return FromKilogramsPerSecond(value.Value); - case MassFlowUnit.MegapoundPerHour: - return FromMegapoundsPerHour(value.Value); - case MassFlowUnit.MicrogramPerSecond: - return FromMicrogramsPerSecond(value.Value); - case MassFlowUnit.MilligramPerSecond: - return FromMilligramsPerSecond(value.Value); - case MassFlowUnit.NanogramPerSecond: - return FromNanogramsPerSecond(value.Value); - case MassFlowUnit.PoundPerHour: - return FromPoundsPerHour(value.Value); - case MassFlowUnit.ShortTonPerHour: - return FromShortTonsPerHour(value.Value); - case MassFlowUnit.TonnePerDay: - return FromTonnesPerDay(value.Value); - case MassFlowUnit.TonnePerHour: - return FromTonnesPerHour(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MassFlow((double)value.Value, fromUnit); } #endif @@ -877,12 +719,29 @@ public static string GetAbbreviation(MassFlowUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MassFlowUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MassFlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -893,37 +752,37 @@ public static string GetAbbreviation(MassFlowUnit unit, [CanBeNull] Culture cult #if !WINDOWS_UWP public static MassFlow operator -(MassFlow right) { - return new MassFlow(-right._gramsPerSecond); + return new MassFlow(-right.Value, right.Unit); } public static MassFlow operator +(MassFlow left, MassFlow right) { - return new MassFlow(left._gramsPerSecond + right._gramsPerSecond); + return new MassFlow(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static MassFlow operator -(MassFlow left, MassFlow right) { - return new MassFlow(left._gramsPerSecond - right._gramsPerSecond); + return new MassFlow(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static MassFlow operator *(double left, MassFlow right) { - return new MassFlow(left*right._gramsPerSecond); + return new MassFlow(left * right.Value, right.Unit); } public static MassFlow operator *(MassFlow left, double right) { - return new MassFlow(left._gramsPerSecond*(double)right); + return new MassFlow(left.Value * right, left.Unit); } public static MassFlow operator /(MassFlow left, double right) { - return new MassFlow(left._gramsPerSecond/(double)right); + return new MassFlow(left.Value / right, left.Unit); } public static double operator /(MassFlow left, MassFlow right) { - return Convert.ToDouble(left._gramsPerSecond/right._gramsPerSecond); + return left.GramsPerSecond / right.GramsPerSecond; } #endif @@ -946,43 +805,43 @@ public int CompareTo(object obj) #endif int CompareTo(MassFlow other) { - return _gramsPerSecond.CompareTo(other._gramsPerSecond); + return AsBaseUnitGramsPerSecond().CompareTo(other.AsBaseUnitGramsPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(MassFlow left, MassFlow right) { - return left._gramsPerSecond <= right._gramsPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(MassFlow left, MassFlow right) { - return left._gramsPerSecond >= right._gramsPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(MassFlow left, MassFlow right) { - return left._gramsPerSecond < right._gramsPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(MassFlow left, MassFlow right) { - return left._gramsPerSecond > right._gramsPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(MassFlow left, MassFlow right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._gramsPerSecond == right._gramsPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(MassFlow left, MassFlow right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._gramsPerSecond != right._gramsPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -994,7 +853,7 @@ public override bool Equals(object obj) return false; } - return _gramsPerSecond.Equals(((MassFlow) obj)._gramsPerSecond); + return AsBaseUnitGramsPerSecond().Equals(((MassFlow) obj).AsBaseUnitGramsPerSecond()); } /// @@ -1007,12 +866,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(MassFlow other, MassFlow maxError) { - return Math.Abs(_gramsPerSecond - other._gramsPerSecond) <= maxError._gramsPerSecond; + return Math.Abs(AsBaseUnitGramsPerSecond() - other.AsBaseUnitGramsPerSecond()) <= maxError.AsBaseUnitGramsPerSecond(); } public override int GetHashCode() { - return _gramsPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1022,42 +881,33 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MassFlowUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitGramsPerSecond(); + switch (unit) { - case MassFlowUnit.CentigramPerSecond: - return CentigramsPerSecond; - case MassFlowUnit.DecagramPerSecond: - return DecagramsPerSecond; - case MassFlowUnit.DecigramPerSecond: - return DecigramsPerSecond; - case MassFlowUnit.GramPerSecond: - return GramsPerSecond; - case MassFlowUnit.HectogramPerSecond: - return HectogramsPerSecond; - case MassFlowUnit.KilogramPerHour: - return KilogramsPerHour; - case MassFlowUnit.KilogramPerSecond: - return KilogramsPerSecond; - case MassFlowUnit.MegapoundPerHour: - return MegapoundsPerHour; - case MassFlowUnit.MicrogramPerSecond: - return MicrogramsPerSecond; - case MassFlowUnit.MilligramPerSecond: - return MilligramsPerSecond; - case MassFlowUnit.NanogramPerSecond: - return NanogramsPerSecond; - case MassFlowUnit.PoundPerHour: - return PoundsPerHour; - case MassFlowUnit.ShortTonPerHour: - return ShortTonsPerHour; - case MassFlowUnit.TonnePerDay: - return TonnesPerDay; - case MassFlowUnit.TonnePerHour: - return TonnesPerHour; + case MassFlowUnit.CentigramPerSecond: return (baseUnitValue) / 1e-2d; + case MassFlowUnit.DecagramPerSecond: return (baseUnitValue) / 1e1d; + case MassFlowUnit.DecigramPerSecond: return (baseUnitValue) / 1e-1d; + case MassFlowUnit.GramPerSecond: return baseUnitValue; + case MassFlowUnit.HectogramPerSecond: return (baseUnitValue) / 1e2d; + case MassFlowUnit.KilogramPerHour: return baseUnitValue*3.6; + case MassFlowUnit.KilogramPerSecond: return (baseUnitValue) / 1e3d; + case MassFlowUnit.MegapoundPerHour: return (baseUnitValue*7.93664) / 1e6d; + case MassFlowUnit.MicrogramPerSecond: return (baseUnitValue) / 1e-6d; + case MassFlowUnit.MilligramPerSecond: return (baseUnitValue) / 1e-3d; + case MassFlowUnit.NanogramPerSecond: return (baseUnitValue) / 1e-9d; + case MassFlowUnit.PoundPerHour: return baseUnitValue*7.93664; + case MassFlowUnit.ShortTonPerHour: return baseUnitValue/251.9957611; + case MassFlowUnit.TonnePerDay: return baseUnitValue*0.0864000; + case MassFlowUnit.TonnePerHour: return baseUnitValue*3.6/1000; default: throw new NotImplementedException("unit: " + unit); @@ -1099,7 +949,11 @@ public static MassFlow Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1118,17 +972,24 @@ public static MassFlow Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MassFlow Parse(string str, [CanBeNull] Culture culture) + public static MassFlow Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1154,16 +1015,41 @@ public static bool TryParse([CanBeNull] string str, out MassFlow result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out MassFlow result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out MassFlow result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1176,6 +1062,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1189,11 +1076,14 @@ public static MassFlowUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MassFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1202,6 +1092,8 @@ public static MassFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1214,18 +1106,18 @@ public static MassFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static MassFlowUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MassFlowUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MassFlowUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassFlowUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1234,6 +1126,7 @@ static MassFlowUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is GramPerSecond /// @@ -1245,7 +1138,7 @@ static MassFlowUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1262,74 +1155,143 @@ public string ToString(MassFlowUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MassFlowUnit unit, [CanBeNull] Culture culture) + public string ToString( + MassFlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MassFlowUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MassFlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MassFlowUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MassFlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of MassFlow /// - public static MassFlow MaxValue - { - get - { - return new MassFlow(double.MaxValue); - } - } + public static MassFlow MaxValue => new MassFlow(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of MassFlow /// - public static MassFlow MinValue + public static MassFlow MinValue => new MassFlow(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitGramsPerSecond() { - get + if (Unit == MassFlowUnit.GramPerSecond) { return _value; } + + switch (Unit) { - return new MassFlow(double.MinValue); - } - } - } + case MassFlowUnit.CentigramPerSecond: return (_value) * 1e-2d; + case MassFlowUnit.DecagramPerSecond: return (_value) * 1e1d; + case MassFlowUnit.DecigramPerSecond: return (_value) * 1e-1d; + case MassFlowUnit.GramPerSecond: return _value; + case MassFlowUnit.HectogramPerSecond: return (_value) * 1e2d; + case MassFlowUnit.KilogramPerHour: return _value/3.6; + case MassFlowUnit.KilogramPerSecond: return (_value) * 1e3d; + case MassFlowUnit.MegapoundPerHour: return (_value/7.93664) * 1e6d; + case MassFlowUnit.MicrogramPerSecond: return (_value) * 1e-6d; + case MassFlowUnit.MilligramPerSecond: return (_value) * 1e-3d; + case MassFlowUnit.NanogramPerSecond: return (_value) * 1e-9d; + case MassFlowUnit.PoundPerHour: return _value/7.93664; + case MassFlowUnit.ShortTonPerHour: return _value*251.9957611; + case MassFlowUnit.TonnePerDay: return _value/0.0864000; + case MassFlowUnit.TonnePerHour: return 1000*_value/3.6; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MassFlowUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs index 3aba1ebeff..785e3502ba 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct MassFlux : IComparable, IComparable #endif { /// - /// Base unit of MassFlux. + /// The numeric value this quantity was constructed with. /// - private readonly double _kilogramsPerSecondPerSquareMeter; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassFluxUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public MassFlux() : this(0) + public MassFlux() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public MassFlux(double kilogramspersecondpersquaremeter) { - _kilogramsPerSecondPerSquareMeter = Convert.ToDouble(kilogramspersecondpersquaremeter); + _value = Convert.ToDouble(kilogramspersecondpersquaremeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + MassFlux(double numericValue, MassFluxUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerSecondPerSquareMeter. + /// + /// Value assuming base unit KilogramPerSecondPerSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MassFlux(long kilogramspersecondpersquaremeter) - { - _kilogramsPerSecondPerSquareMeter = Convert.ToDouble(kilogramspersecondpersquaremeter); - } + MassFlux(long kilogramspersecondpersquaremeter) : this(Convert.ToDouble(kilogramspersecondpersquaremeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerSecondPerSquareMeter. + /// + /// Value assuming base unit KilogramPerSecondPerSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MassFlux(decimal kilogramspersecondpersquaremeter) - { - _kilogramsPerSecondPerSquareMeter = Convert.ToDouble(kilogramspersecondpersquaremeter); - } + MassFlux(decimal kilogramspersecondpersquaremeter) : this(Convert.ToDouble(kilogramspersecondpersquaremeter), BaseUnit) { } #region Properties @@ -119,40 +156,26 @@ public MassFlux(double kilogramspersecondpersquaremeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MassFluxUnit BaseUnit - { - get { return MassFluxUnit.KilogramPerSecondPerSquareMeter; } - } + public static MassFluxUnit BaseUnit => MassFluxUnit.KilogramPerSecondPerSquareMeter; /// /// All units of measurement for the MassFlux quantity. /// public static MassFluxUnit[] Units { get; } = Enum.GetValues(typeof(MassFluxUnit)).Cast().ToArray(); - /// /// Get MassFlux in GramsPerSecondPerSquareMeter. /// - public double GramsPerSecondPerSquareMeter - { - get { return _kilogramsPerSecondPerSquareMeter*1e3; } - } - + public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); /// /// Get MassFlux in KilogramsPerSecondPerSquareMeter. /// - public double KilogramsPerSecondPerSquareMeter - { - get { return (_kilogramsPerSecondPerSquareMeter*1e3) / 1e3d; } - } + public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); #endregion #region Static - public static MassFlux Zero - { - get { return new MassFlux(); } - } + public static MassFlux Zero => new MassFlux(0, BaseUnit); /// /// Get MassFlux from GramsPerSecondPerSquareMeter. @@ -160,17 +183,13 @@ public static MassFlux Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlux FromGramsPerSecondPerSquareMeter(double gramspersecondpersquaremeter) - { - double value = (double) gramspersecondpersquaremeter; - return new MassFlux(value/1e3); - } #else public static MassFlux FromGramsPerSecondPerSquareMeter(QuantityValue gramspersecondpersquaremeter) +#endif { double value = (double) gramspersecondpersquaremeter; - return new MassFlux((value/1e3)); + return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); } -#endif /// /// Get MassFlux from KilogramsPerSecondPerSquareMeter. @@ -178,17 +197,13 @@ public static MassFlux FromGramsPerSecondPerSquareMeter(QuantityValue gramsperse #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassFlux FromKilogramsPerSecondPerSquareMeter(double kilogramspersecondpersquaremeter) - { - double value = (double) kilogramspersecondpersquaremeter; - return new MassFlux((value/1e3) * 1e3d); - } #else public static MassFlux FromKilogramsPerSecondPerSquareMeter(QuantityValue kilogramspersecondpersquaremeter) +#endif { double value = (double) kilogramspersecondpersquaremeter; - return new MassFlux(((value/1e3) * 1e3d)); + return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -238,16 +253,7 @@ public static MassFlux From(double value, MassFluxUnit fromUnit) public static MassFlux From(QuantityValue value, MassFluxUnit fromUnit) #endif { - switch (fromUnit) - { - case MassFluxUnit.GramPerSecondPerSquareMeter: - return FromGramsPerSecondPerSquareMeter(value); - case MassFluxUnit.KilogramPerSecondPerSquareMeter: - return FromKilogramsPerSecondPerSquareMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MassFlux((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -264,16 +270,8 @@ public static MassFlux From(QuantityValue value, MassFluxUnit fromUnit) { return null; } - switch (fromUnit) - { - case MassFluxUnit.GramPerSecondPerSquareMeter: - return FromGramsPerSecondPerSquareMeter(value.Value); - case MassFluxUnit.KilogramPerSecondPerSquareMeter: - return FromKilogramsPerSecondPerSquareMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MassFlux((double)value.Value, fromUnit); } #endif @@ -292,12 +290,29 @@ public static string GetAbbreviation(MassFluxUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MassFluxUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MassFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -308,37 +323,37 @@ public static string GetAbbreviation(MassFluxUnit unit, [CanBeNull] Culture cult #if !WINDOWS_UWP public static MassFlux operator -(MassFlux right) { - return new MassFlux(-right._kilogramsPerSecondPerSquareMeter); + return new MassFlux(-right.Value, right.Unit); } public static MassFlux operator +(MassFlux left, MassFlux right) { - return new MassFlux(left._kilogramsPerSecondPerSquareMeter + right._kilogramsPerSecondPerSquareMeter); + return new MassFlux(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static MassFlux operator -(MassFlux left, MassFlux right) { - return new MassFlux(left._kilogramsPerSecondPerSquareMeter - right._kilogramsPerSecondPerSquareMeter); + return new MassFlux(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static MassFlux operator *(double left, MassFlux right) { - return new MassFlux(left*right._kilogramsPerSecondPerSquareMeter); + return new MassFlux(left * right.Value, right.Unit); } public static MassFlux operator *(MassFlux left, double right) { - return new MassFlux(left._kilogramsPerSecondPerSquareMeter*(double)right); + return new MassFlux(left.Value * right, left.Unit); } public static MassFlux operator /(MassFlux left, double right) { - return new MassFlux(left._kilogramsPerSecondPerSquareMeter/(double)right); + return new MassFlux(left.Value / right, left.Unit); } public static double operator /(MassFlux left, MassFlux right) { - return Convert.ToDouble(left._kilogramsPerSecondPerSquareMeter/right._kilogramsPerSecondPerSquareMeter); + return left.KilogramsPerSecondPerSquareMeter / right.KilogramsPerSecondPerSquareMeter; } #endif @@ -361,43 +376,43 @@ public int CompareTo(object obj) #endif int CompareTo(MassFlux other) { - return _kilogramsPerSecondPerSquareMeter.CompareTo(other._kilogramsPerSecondPerSquareMeter); + return AsBaseUnitKilogramsPerSecondPerSquareMeter().CompareTo(other.AsBaseUnitKilogramsPerSecondPerSquareMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(MassFlux left, MassFlux right) { - return left._kilogramsPerSecondPerSquareMeter <= right._kilogramsPerSecondPerSquareMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(MassFlux left, MassFlux right) { - return left._kilogramsPerSecondPerSquareMeter >= right._kilogramsPerSecondPerSquareMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(MassFlux left, MassFlux right) { - return left._kilogramsPerSecondPerSquareMeter < right._kilogramsPerSecondPerSquareMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(MassFlux left, MassFlux right) { - return left._kilogramsPerSecondPerSquareMeter > right._kilogramsPerSecondPerSquareMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(MassFlux left, MassFlux right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerSecondPerSquareMeter == right._kilogramsPerSecondPerSquareMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(MassFlux left, MassFlux right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerSecondPerSquareMeter != right._kilogramsPerSecondPerSquareMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -409,7 +424,7 @@ public override bool Equals(object obj) return false; } - return _kilogramsPerSecondPerSquareMeter.Equals(((MassFlux) obj)._kilogramsPerSecondPerSquareMeter); + return AsBaseUnitKilogramsPerSecondPerSquareMeter().Equals(((MassFlux) obj).AsBaseUnitKilogramsPerSecondPerSquareMeter()); } /// @@ -422,12 +437,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(MassFlux other, MassFlux maxError) { - return Math.Abs(_kilogramsPerSecondPerSquareMeter - other._kilogramsPerSecondPerSquareMeter) <= maxError._kilogramsPerSecondPerSquareMeter; + return Math.Abs(AsBaseUnitKilogramsPerSecondPerSquareMeter() - other.AsBaseUnitKilogramsPerSecondPerSquareMeter()) <= maxError.AsBaseUnitKilogramsPerSecondPerSquareMeter(); } public override int GetHashCode() { - return _kilogramsPerSecondPerSquareMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -437,16 +452,20 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MassFluxUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitKilogramsPerSecondPerSquareMeter(); + switch (unit) { - case MassFluxUnit.GramPerSecondPerSquareMeter: - return GramsPerSecondPerSquareMeter; - case MassFluxUnit.KilogramPerSecondPerSquareMeter: - return KilogramsPerSecondPerSquareMeter; + case MassFluxUnit.GramPerSecondPerSquareMeter: return baseUnitValue*1e3; + case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (baseUnitValue*1e3) / 1e3d; default: throw new NotImplementedException("unit: " + unit); @@ -488,7 +507,11 @@ public static MassFlux Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -507,17 +530,24 @@ public static MassFlux Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MassFlux Parse(string str, [CanBeNull] Culture culture) + public static MassFlux Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -543,16 +573,41 @@ public static bool TryParse([CanBeNull] string str, out MassFlux result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out MassFlux result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out MassFlux result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -565,6 +620,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -578,11 +634,14 @@ public static MassFluxUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MassFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -591,6 +650,8 @@ public static MassFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -603,18 +664,18 @@ public static MassFluxUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static MassFluxUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MassFluxUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MassFluxUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassFluxUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -623,6 +684,7 @@ static MassFluxUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is KilogramPerSecondPerSquareMeter /// @@ -634,7 +696,7 @@ static MassFluxUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -651,74 +713,130 @@ public string ToString(MassFluxUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MassFluxUnit unit, [CanBeNull] Culture culture) + public string ToString( + MassFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MassFluxUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MassFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MassFluxUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MassFluxUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of MassFlux /// - public static MassFlux MaxValue - { - get - { - return new MassFlux(double.MaxValue); - } - } + public static MassFlux MaxValue => new MassFlux(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of MassFlux /// - public static MassFlux MinValue + public static MassFlux MinValue => new MassFlux(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitKilogramsPerSecondPerSquareMeter() { - get + if (Unit == MassFluxUnit.KilogramPerSecondPerSquareMeter) { return _value; } + + switch (Unit) { - return new MassFlux(double.MinValue); - } - } - } + case MassFluxUnit.GramPerSecondPerSquareMeter: return _value/1e3; + case MassFluxUnit.KilogramPerSecondPerSquareMeter: return (_value/1e3) * 1e3d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MassFluxUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs index 79103b0ce0..ff67ff1167 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct MassMomentOfInertia : IComparable, IComparable - /// Base unit of MassMomentOfInertia. + /// The numeric value this quantity was constructed with. /// - private readonly double _kilogramSquareMeters; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MassMomentOfInertiaUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public MassMomentOfInertia() : this(0) + public MassMomentOfInertia() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public MassMomentOfInertia(double kilogramsquaremeters) { - _kilogramSquareMeters = Convert.ToDouble(kilogramsquaremeters); + _value = Convert.ToDouble(kilogramsquaremeters); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + MassMomentOfInertia(double numericValue, MassMomentOfInertiaUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit KilogramSquareMeter. + /// + /// Value assuming base unit KilogramSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MassMomentOfInertia(long kilogramsquaremeters) - { - _kilogramSquareMeters = Convert.ToDouble(kilogramsquaremeters); - } + MassMomentOfInertia(long kilogramsquaremeters) : this(Convert.ToDouble(kilogramsquaremeters), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit KilogramSquareMeter. + /// + /// Value assuming base unit KilogramSquareMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MassMomentOfInertia(decimal kilogramsquaremeters) - { - _kilogramSquareMeters = Convert.ToDouble(kilogramsquaremeters); - } + MassMomentOfInertia(decimal kilogramsquaremeters) : this(Convert.ToDouble(kilogramsquaremeters), BaseUnit) { } #region Properties @@ -119,232 +156,122 @@ public MassMomentOfInertia(double kilogramsquaremeters) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MassMomentOfInertiaUnit BaseUnit - { - get { return MassMomentOfInertiaUnit.KilogramSquareMeter; } - } + public static MassMomentOfInertiaUnit BaseUnit => MassMomentOfInertiaUnit.KilogramSquareMeter; /// /// All units of measurement for the MassMomentOfInertia quantity. /// public static MassMomentOfInertiaUnit[] Units { get; } = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().ToArray(); - /// /// Get MassMomentOfInertia in GramSquareCentimeters. /// - public double GramSquareCentimeters - { - get { return _kilogramSquareMeters*1e7; } - } - + public double GramSquareCentimeters => As(MassMomentOfInertiaUnit.GramSquareCentimeter); /// /// Get MassMomentOfInertia in GramSquareDecimeters. /// - public double GramSquareDecimeters - { - get { return _kilogramSquareMeters*1e5; } - } - + public double GramSquareDecimeters => As(MassMomentOfInertiaUnit.GramSquareDecimeter); /// /// Get MassMomentOfInertia in GramSquareMeters. /// - public double GramSquareMeters - { - get { return _kilogramSquareMeters*1e3; } - } - + public double GramSquareMeters => As(MassMomentOfInertiaUnit.GramSquareMeter); /// /// Get MassMomentOfInertia in GramSquareMillimeters. /// - public double GramSquareMillimeters - { - get { return _kilogramSquareMeters*1e9; } - } - + public double GramSquareMillimeters => As(MassMomentOfInertiaUnit.GramSquareMillimeter); /// /// Get MassMomentOfInertia in KilogramSquareCentimeters. /// - public double KilogramSquareCentimeters - { - get { return (_kilogramSquareMeters*1e7) / 1e3d; } - } - + public double KilogramSquareCentimeters => As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); /// /// Get MassMomentOfInertia in KilogramSquareDecimeters. /// - public double KilogramSquareDecimeters - { - get { return (_kilogramSquareMeters*1e5) / 1e3d; } - } - + public double KilogramSquareDecimeters => As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); /// /// Get MassMomentOfInertia in KilogramSquareMeters. /// - public double KilogramSquareMeters - { - get { return (_kilogramSquareMeters*1e3) / 1e3d; } - } - + public double KilogramSquareMeters => As(MassMomentOfInertiaUnit.KilogramSquareMeter); /// /// Get MassMomentOfInertia in KilogramSquareMillimeters. /// - public double KilogramSquareMillimeters - { - get { return (_kilogramSquareMeters*1e9) / 1e3d; } - } - + public double KilogramSquareMillimeters => As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); /// /// Get MassMomentOfInertia in KilotonneSquareCentimeters. /// - public double KilotonneSquareCentimeters - { - get { return (_kilogramSquareMeters*1e1) / 1e3d; } - } - + public double KilotonneSquareCentimeters => As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); /// /// Get MassMomentOfInertia in KilotonneSquareDecimeters. /// - public double KilotonneSquareDecimeters - { - get { return (_kilogramSquareMeters*1e-1) / 1e3d; } - } - + public double KilotonneSquareDecimeters => As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); /// /// Get MassMomentOfInertia in KilotonneSquareMeters. /// - public double KilotonneSquareMeters - { - get { return (_kilogramSquareMeters*1e-3) / 1e3d; } - } - + public double KilotonneSquareMeters => As(MassMomentOfInertiaUnit.KilotonneSquareMeter); /// /// Get MassMomentOfInertia in KilotonneSquareMilimeters. /// - public double KilotonneSquareMilimeters - { - get { return (_kilogramSquareMeters*1e3) / 1e3d; } - } - + public double KilotonneSquareMilimeters => As(MassMomentOfInertiaUnit.KilotonneSquareMilimeter); /// /// Get MassMomentOfInertia in MegatonneSquareCentimeters. /// - public double MegatonneSquareCentimeters - { - get { return (_kilogramSquareMeters*1e1) / 1e6d; } - } - + public double MegatonneSquareCentimeters => As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); /// /// Get MassMomentOfInertia in MegatonneSquareDecimeters. /// - public double MegatonneSquareDecimeters - { - get { return (_kilogramSquareMeters*1e-1) / 1e6d; } - } - + public double MegatonneSquareDecimeters => As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); /// /// Get MassMomentOfInertia in MegatonneSquareMeters. /// - public double MegatonneSquareMeters - { - get { return (_kilogramSquareMeters*1e-3) / 1e6d; } - } - + public double MegatonneSquareMeters => As(MassMomentOfInertiaUnit.MegatonneSquareMeter); /// /// Get MassMomentOfInertia in MegatonneSquareMilimeters. /// - public double MegatonneSquareMilimeters - { - get { return (_kilogramSquareMeters*1e3) / 1e6d; } - } - + public double MegatonneSquareMilimeters => As(MassMomentOfInertiaUnit.MegatonneSquareMilimeter); /// /// Get MassMomentOfInertia in MilligramSquareCentimeters. /// - public double MilligramSquareCentimeters - { - get { return (_kilogramSquareMeters*1e7) / 1e-3d; } - } - + public double MilligramSquareCentimeters => As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); /// /// Get MassMomentOfInertia in MilligramSquareDecimeters. /// - public double MilligramSquareDecimeters - { - get { return (_kilogramSquareMeters*1e5) / 1e-3d; } - } - + public double MilligramSquareDecimeters => As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); /// /// Get MassMomentOfInertia in MilligramSquareMeters. /// - public double MilligramSquareMeters - { - get { return (_kilogramSquareMeters*1e3) / 1e-3d; } - } - + public double MilligramSquareMeters => As(MassMomentOfInertiaUnit.MilligramSquareMeter); /// /// Get MassMomentOfInertia in MilligramSquareMillimeters. /// - public double MilligramSquareMillimeters - { - get { return (_kilogramSquareMeters*1e9) / 1e-3d; } - } - + public double MilligramSquareMillimeters => As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); /// /// Get MassMomentOfInertia in PoundSquareFeet. /// - public double PoundSquareFeet - { - get { return _kilogramSquareMeters/4.21401101e-2; } - } - + public double PoundSquareFeet => As(MassMomentOfInertiaUnit.PoundSquareFoot); /// /// Get MassMomentOfInertia in PoundSquareInches. /// - public double PoundSquareInches - { - get { return _kilogramSquareMeters/2.9263965e-4; } - } - + public double PoundSquareInches => As(MassMomentOfInertiaUnit.PoundSquareInch); /// /// Get MassMomentOfInertia in TonneSquareCentimeters. /// - public double TonneSquareCentimeters - { - get { return _kilogramSquareMeters*1e1; } - } - + public double TonneSquareCentimeters => As(MassMomentOfInertiaUnit.TonneSquareCentimeter); /// /// Get MassMomentOfInertia in TonneSquareDecimeters. /// - public double TonneSquareDecimeters - { - get { return _kilogramSquareMeters*1e-1; } - } - + public double TonneSquareDecimeters => As(MassMomentOfInertiaUnit.TonneSquareDecimeter); /// /// Get MassMomentOfInertia in TonneSquareMeters. /// - public double TonneSquareMeters - { - get { return _kilogramSquareMeters*1e-3; } - } - + public double TonneSquareMeters => As(MassMomentOfInertiaUnit.TonneSquareMeter); /// /// Get MassMomentOfInertia in TonneSquareMilimeters. /// - public double TonneSquareMilimeters - { - get { return _kilogramSquareMeters*1e3; } - } + public double TonneSquareMilimeters => As(MassMomentOfInertiaUnit.TonneSquareMilimeter); #endregion #region Static - public static MassMomentOfInertia Zero - { - get { return new MassMomentOfInertia(); } - } + public static MassMomentOfInertia Zero => new MassMomentOfInertia(0, BaseUnit); /// /// Get MassMomentOfInertia from GramSquareCentimeters. @@ -352,17 +279,13 @@ public static MassMomentOfInertia Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromGramSquareCentimeters(double gramsquarecentimeters) - { - double value = (double) gramsquarecentimeters; - return new MassMomentOfInertia(value/1e7); - } #else public static MassMomentOfInertia FromGramSquareCentimeters(QuantityValue gramsquarecentimeters) +#endif { double value = (double) gramsquarecentimeters; - return new MassMomentOfInertia((value/1e7)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); } -#endif /// /// Get MassMomentOfInertia from GramSquareDecimeters. @@ -370,17 +293,13 @@ public static MassMomentOfInertia FromGramSquareCentimeters(QuantityValue gramsq #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromGramSquareDecimeters(double gramsquaredecimeters) - { - double value = (double) gramsquaredecimeters; - return new MassMomentOfInertia(value/1e5); - } #else public static MassMomentOfInertia FromGramSquareDecimeters(QuantityValue gramsquaredecimeters) +#endif { double value = (double) gramsquaredecimeters; - return new MassMomentOfInertia((value/1e5)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); } -#endif /// /// Get MassMomentOfInertia from GramSquareMeters. @@ -388,17 +307,13 @@ public static MassMomentOfInertia FromGramSquareDecimeters(QuantityValue gramsqu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromGramSquareMeters(double gramsquaremeters) - { - double value = (double) gramsquaremeters; - return new MassMomentOfInertia(value/1e3); - } #else public static MassMomentOfInertia FromGramSquareMeters(QuantityValue gramsquaremeters) +#endif { double value = (double) gramsquaremeters; - return new MassMomentOfInertia((value/1e3)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); } -#endif /// /// Get MassMomentOfInertia from GramSquareMillimeters. @@ -406,17 +321,13 @@ public static MassMomentOfInertia FromGramSquareMeters(QuantityValue gramsquarem #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromGramSquareMillimeters(double gramsquaremillimeters) - { - double value = (double) gramsquaremillimeters; - return new MassMomentOfInertia(value/1e9); - } #else public static MassMomentOfInertia FromGramSquareMillimeters(QuantityValue gramsquaremillimeters) +#endif { double value = (double) gramsquaremillimeters; - return new MassMomentOfInertia((value/1e9)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); } -#endif /// /// Get MassMomentOfInertia from KilogramSquareCentimeters. @@ -424,17 +335,13 @@ public static MassMomentOfInertia FromGramSquareMillimeters(QuantityValue gramsq #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromKilogramSquareCentimeters(double kilogramsquarecentimeters) - { - double value = (double) kilogramsquarecentimeters; - return new MassMomentOfInertia((value/1e7) * 1e3d); - } #else public static MassMomentOfInertia FromKilogramSquareCentimeters(QuantityValue kilogramsquarecentimeters) +#endif { double value = (double) kilogramsquarecentimeters; - return new MassMomentOfInertia(((value/1e7) * 1e3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); } -#endif /// /// Get MassMomentOfInertia from KilogramSquareDecimeters. @@ -442,17 +349,13 @@ public static MassMomentOfInertia FromKilogramSquareCentimeters(QuantityValue ki #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromKilogramSquareDecimeters(double kilogramsquaredecimeters) - { - double value = (double) kilogramsquaredecimeters; - return new MassMomentOfInertia((value/1e5) * 1e3d); - } #else public static MassMomentOfInertia FromKilogramSquareDecimeters(QuantityValue kilogramsquaredecimeters) +#endif { double value = (double) kilogramsquaredecimeters; - return new MassMomentOfInertia(((value/1e5) * 1e3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); } -#endif /// /// Get MassMomentOfInertia from KilogramSquareMeters. @@ -460,17 +363,13 @@ public static MassMomentOfInertia FromKilogramSquareDecimeters(QuantityValue kil #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromKilogramSquareMeters(double kilogramsquaremeters) - { - double value = (double) kilogramsquaremeters; - return new MassMomentOfInertia((value/1e3) * 1e3d); - } #else public static MassMomentOfInertia FromKilogramSquareMeters(QuantityValue kilogramsquaremeters) +#endif { double value = (double) kilogramsquaremeters; - return new MassMomentOfInertia(((value/1e3) * 1e3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); } -#endif /// /// Get MassMomentOfInertia from KilogramSquareMillimeters. @@ -478,17 +377,13 @@ public static MassMomentOfInertia FromKilogramSquareMeters(QuantityValue kilogra #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromKilogramSquareMillimeters(double kilogramsquaremillimeters) - { - double value = (double) kilogramsquaremillimeters; - return new MassMomentOfInertia((value/1e9) * 1e3d); - } #else public static MassMomentOfInertia FromKilogramSquareMillimeters(QuantityValue kilogramsquaremillimeters) +#endif { double value = (double) kilogramsquaremillimeters; - return new MassMomentOfInertia(((value/1e9) * 1e3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); } -#endif /// /// Get MassMomentOfInertia from KilotonneSquareCentimeters. @@ -496,17 +391,13 @@ public static MassMomentOfInertia FromKilogramSquareMillimeters(QuantityValue ki #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromKilotonneSquareCentimeters(double kilotonnesquarecentimeters) - { - double value = (double) kilotonnesquarecentimeters; - return new MassMomentOfInertia((value/1e1) * 1e3d); - } #else public static MassMomentOfInertia FromKilotonneSquareCentimeters(QuantityValue kilotonnesquarecentimeters) +#endif { double value = (double) kilotonnesquarecentimeters; - return new MassMomentOfInertia(((value/1e1) * 1e3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); } -#endif /// /// Get MassMomentOfInertia from KilotonneSquareDecimeters. @@ -514,17 +405,13 @@ public static MassMomentOfInertia FromKilotonneSquareCentimeters(QuantityValue k #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromKilotonneSquareDecimeters(double kilotonnesquaredecimeters) - { - double value = (double) kilotonnesquaredecimeters; - return new MassMomentOfInertia((value/1e-1) * 1e3d); - } #else public static MassMomentOfInertia FromKilotonneSquareDecimeters(QuantityValue kilotonnesquaredecimeters) +#endif { double value = (double) kilotonnesquaredecimeters; - return new MassMomentOfInertia(((value/1e-1) * 1e3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); } -#endif /// /// Get MassMomentOfInertia from KilotonneSquareMeters. @@ -532,17 +419,13 @@ public static MassMomentOfInertia FromKilotonneSquareDecimeters(QuantityValue ki #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromKilotonneSquareMeters(double kilotonnesquaremeters) - { - double value = (double) kilotonnesquaremeters; - return new MassMomentOfInertia((value/1e-3) * 1e3d); - } #else public static MassMomentOfInertia FromKilotonneSquareMeters(QuantityValue kilotonnesquaremeters) +#endif { double value = (double) kilotonnesquaremeters; - return new MassMomentOfInertia(((value/1e-3) * 1e3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); } -#endif /// /// Get MassMomentOfInertia from KilotonneSquareMilimeters. @@ -550,17 +433,13 @@ public static MassMomentOfInertia FromKilotonneSquareMeters(QuantityValue kiloto #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromKilotonneSquareMilimeters(double kilotonnesquaremilimeters) - { - double value = (double) kilotonnesquaremilimeters; - return new MassMomentOfInertia((value/1e3) * 1e3d); - } #else public static MassMomentOfInertia FromKilotonneSquareMilimeters(QuantityValue kilotonnesquaremilimeters) +#endif { double value = (double) kilotonnesquaremilimeters; - return new MassMomentOfInertia(((value/1e3) * 1e3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMilimeter); } -#endif /// /// Get MassMomentOfInertia from MegatonneSquareCentimeters. @@ -568,17 +447,13 @@ public static MassMomentOfInertia FromKilotonneSquareMilimeters(QuantityValue ki #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromMegatonneSquareCentimeters(double megatonnesquarecentimeters) - { - double value = (double) megatonnesquarecentimeters; - return new MassMomentOfInertia((value/1e1) * 1e6d); - } #else public static MassMomentOfInertia FromMegatonneSquareCentimeters(QuantityValue megatonnesquarecentimeters) +#endif { double value = (double) megatonnesquarecentimeters; - return new MassMomentOfInertia(((value/1e1) * 1e6d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); } -#endif /// /// Get MassMomentOfInertia from MegatonneSquareDecimeters. @@ -586,17 +461,13 @@ public static MassMomentOfInertia FromMegatonneSquareCentimeters(QuantityValue m #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromMegatonneSquareDecimeters(double megatonnesquaredecimeters) - { - double value = (double) megatonnesquaredecimeters; - return new MassMomentOfInertia((value/1e-1) * 1e6d); - } #else public static MassMomentOfInertia FromMegatonneSquareDecimeters(QuantityValue megatonnesquaredecimeters) +#endif { double value = (double) megatonnesquaredecimeters; - return new MassMomentOfInertia(((value/1e-1) * 1e6d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); } -#endif /// /// Get MassMomentOfInertia from MegatonneSquareMeters. @@ -604,17 +475,13 @@ public static MassMomentOfInertia FromMegatonneSquareDecimeters(QuantityValue me #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromMegatonneSquareMeters(double megatonnesquaremeters) - { - double value = (double) megatonnesquaremeters; - return new MassMomentOfInertia((value/1e-3) * 1e6d); - } #else public static MassMomentOfInertia FromMegatonneSquareMeters(QuantityValue megatonnesquaremeters) +#endif { double value = (double) megatonnesquaremeters; - return new MassMomentOfInertia(((value/1e-3) * 1e6d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); } -#endif /// /// Get MassMomentOfInertia from MegatonneSquareMilimeters. @@ -622,17 +489,13 @@ public static MassMomentOfInertia FromMegatonneSquareMeters(QuantityValue megato #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromMegatonneSquareMilimeters(double megatonnesquaremilimeters) - { - double value = (double) megatonnesquaremilimeters; - return new MassMomentOfInertia((value/1e3) * 1e6d); - } #else public static MassMomentOfInertia FromMegatonneSquareMilimeters(QuantityValue megatonnesquaremilimeters) +#endif { double value = (double) megatonnesquaremilimeters; - return new MassMomentOfInertia(((value/1e3) * 1e6d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMilimeter); } -#endif /// /// Get MassMomentOfInertia from MilligramSquareCentimeters. @@ -640,17 +503,13 @@ public static MassMomentOfInertia FromMegatonneSquareMilimeters(QuantityValue me #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromMilligramSquareCentimeters(double milligramsquarecentimeters) - { - double value = (double) milligramsquarecentimeters; - return new MassMomentOfInertia((value/1e7) * 1e-3d); - } #else public static MassMomentOfInertia FromMilligramSquareCentimeters(QuantityValue milligramsquarecentimeters) +#endif { double value = (double) milligramsquarecentimeters; - return new MassMomentOfInertia(((value/1e7) * 1e-3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); } -#endif /// /// Get MassMomentOfInertia from MilligramSquareDecimeters. @@ -658,17 +517,13 @@ public static MassMomentOfInertia FromMilligramSquareCentimeters(QuantityValue m #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromMilligramSquareDecimeters(double milligramsquaredecimeters) - { - double value = (double) milligramsquaredecimeters; - return new MassMomentOfInertia((value/1e5) * 1e-3d); - } #else public static MassMomentOfInertia FromMilligramSquareDecimeters(QuantityValue milligramsquaredecimeters) +#endif { double value = (double) milligramsquaredecimeters; - return new MassMomentOfInertia(((value/1e5) * 1e-3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); } -#endif /// /// Get MassMomentOfInertia from MilligramSquareMeters. @@ -676,17 +531,13 @@ public static MassMomentOfInertia FromMilligramSquareDecimeters(QuantityValue mi #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromMilligramSquareMeters(double milligramsquaremeters) - { - double value = (double) milligramsquaremeters; - return new MassMomentOfInertia((value/1e3) * 1e-3d); - } #else public static MassMomentOfInertia FromMilligramSquareMeters(QuantityValue milligramsquaremeters) +#endif { double value = (double) milligramsquaremeters; - return new MassMomentOfInertia(((value/1e3) * 1e-3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); } -#endif /// /// Get MassMomentOfInertia from MilligramSquareMillimeters. @@ -694,17 +545,13 @@ public static MassMomentOfInertia FromMilligramSquareMeters(QuantityValue millig #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromMilligramSquareMillimeters(double milligramsquaremillimeters) - { - double value = (double) milligramsquaremillimeters; - return new MassMomentOfInertia((value/1e9) * 1e-3d); - } #else public static MassMomentOfInertia FromMilligramSquareMillimeters(QuantityValue milligramsquaremillimeters) +#endif { double value = (double) milligramsquaremillimeters; - return new MassMomentOfInertia(((value/1e9) * 1e-3d)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); } -#endif /// /// Get MassMomentOfInertia from PoundSquareFeet. @@ -712,17 +559,13 @@ public static MassMomentOfInertia FromMilligramSquareMillimeters(QuantityValue m #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromPoundSquareFeet(double poundsquarefeet) - { - double value = (double) poundsquarefeet; - return new MassMomentOfInertia(value*4.21401101e-2); - } #else public static MassMomentOfInertia FromPoundSquareFeet(QuantityValue poundsquarefeet) +#endif { double value = (double) poundsquarefeet; - return new MassMomentOfInertia((value*4.21401101e-2)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); } -#endif /// /// Get MassMomentOfInertia from PoundSquareInches. @@ -730,17 +573,13 @@ public static MassMomentOfInertia FromPoundSquareFeet(QuantityValue poundsquaref #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromPoundSquareInches(double poundsquareinches) - { - double value = (double) poundsquareinches; - return new MassMomentOfInertia(value*2.9263965e-4); - } #else public static MassMomentOfInertia FromPoundSquareInches(QuantityValue poundsquareinches) +#endif { double value = (double) poundsquareinches; - return new MassMomentOfInertia((value*2.9263965e-4)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); } -#endif /// /// Get MassMomentOfInertia from TonneSquareCentimeters. @@ -748,17 +587,13 @@ public static MassMomentOfInertia FromPoundSquareInches(QuantityValue poundsquar #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromTonneSquareCentimeters(double tonnesquarecentimeters) - { - double value = (double) tonnesquarecentimeters; - return new MassMomentOfInertia(value/1e1); - } #else public static MassMomentOfInertia FromTonneSquareCentimeters(QuantityValue tonnesquarecentimeters) +#endif { double value = (double) tonnesquarecentimeters; - return new MassMomentOfInertia((value/1e1)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); } -#endif /// /// Get MassMomentOfInertia from TonneSquareDecimeters. @@ -766,17 +601,13 @@ public static MassMomentOfInertia FromTonneSquareCentimeters(QuantityValue tonne #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromTonneSquareDecimeters(double tonnesquaredecimeters) - { - double value = (double) tonnesquaredecimeters; - return new MassMomentOfInertia(value/1e-1); - } #else public static MassMomentOfInertia FromTonneSquareDecimeters(QuantityValue tonnesquaredecimeters) +#endif { double value = (double) tonnesquaredecimeters; - return new MassMomentOfInertia((value/1e-1)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); } -#endif /// /// Get MassMomentOfInertia from TonneSquareMeters. @@ -784,17 +615,13 @@ public static MassMomentOfInertia FromTonneSquareDecimeters(QuantityValue tonnes #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromTonneSquareMeters(double tonnesquaremeters) - { - double value = (double) tonnesquaremeters; - return new MassMomentOfInertia(value/1e-3); - } #else public static MassMomentOfInertia FromTonneSquareMeters(QuantityValue tonnesquaremeters) +#endif { double value = (double) tonnesquaremeters; - return new MassMomentOfInertia((value/1e-3)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); } -#endif /// /// Get MassMomentOfInertia from TonneSquareMilimeters. @@ -802,17 +629,13 @@ public static MassMomentOfInertia FromTonneSquareMeters(QuantityValue tonnesquar #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MassMomentOfInertia FromTonneSquareMilimeters(double tonnesquaremilimeters) - { - double value = (double) tonnesquaremilimeters; - return new MassMomentOfInertia(value/1e3); - } #else public static MassMomentOfInertia FromTonneSquareMilimeters(QuantityValue tonnesquaremilimeters) +#endif { double value = (double) tonnesquaremilimeters; - return new MassMomentOfInertia((value/1e3)); + return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMilimeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1222,64 +1045,7 @@ public static MassMomentOfInertia From(double value, MassMomentOfInertiaUnit fro public static MassMomentOfInertia From(QuantityValue value, MassMomentOfInertiaUnit fromUnit) #endif { - switch (fromUnit) - { - case MassMomentOfInertiaUnit.GramSquareCentimeter: - return FromGramSquareCentimeters(value); - case MassMomentOfInertiaUnit.GramSquareDecimeter: - return FromGramSquareDecimeters(value); - case MassMomentOfInertiaUnit.GramSquareMeter: - return FromGramSquareMeters(value); - case MassMomentOfInertiaUnit.GramSquareMillimeter: - return FromGramSquareMillimeters(value); - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: - return FromKilogramSquareCentimeters(value); - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: - return FromKilogramSquareDecimeters(value); - case MassMomentOfInertiaUnit.KilogramSquareMeter: - return FromKilogramSquareMeters(value); - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: - return FromKilogramSquareMillimeters(value); - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: - return FromKilotonneSquareCentimeters(value); - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: - return FromKilotonneSquareDecimeters(value); - case MassMomentOfInertiaUnit.KilotonneSquareMeter: - return FromKilotonneSquareMeters(value); - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: - return FromKilotonneSquareMilimeters(value); - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: - return FromMegatonneSquareCentimeters(value); - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: - return FromMegatonneSquareDecimeters(value); - case MassMomentOfInertiaUnit.MegatonneSquareMeter: - return FromMegatonneSquareMeters(value); - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: - return FromMegatonneSquareMilimeters(value); - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: - return FromMilligramSquareCentimeters(value); - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: - return FromMilligramSquareDecimeters(value); - case MassMomentOfInertiaUnit.MilligramSquareMeter: - return FromMilligramSquareMeters(value); - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: - return FromMilligramSquareMillimeters(value); - case MassMomentOfInertiaUnit.PoundSquareFoot: - return FromPoundSquareFeet(value); - case MassMomentOfInertiaUnit.PoundSquareInch: - return FromPoundSquareInches(value); - case MassMomentOfInertiaUnit.TonneSquareCentimeter: - return FromTonneSquareCentimeters(value); - case MassMomentOfInertiaUnit.TonneSquareDecimeter: - return FromTonneSquareDecimeters(value); - case MassMomentOfInertiaUnit.TonneSquareMeter: - return FromTonneSquareMeters(value); - case MassMomentOfInertiaUnit.TonneSquareMilimeter: - return FromTonneSquareMilimeters(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MassMomentOfInertia((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1296,64 +1062,8 @@ public static MassMomentOfInertia From(QuantityValue value, MassMomentOfInertiaU { return null; } - switch (fromUnit) - { - case MassMomentOfInertiaUnit.GramSquareCentimeter: - return FromGramSquareCentimeters(value.Value); - case MassMomentOfInertiaUnit.GramSquareDecimeter: - return FromGramSquareDecimeters(value.Value); - case MassMomentOfInertiaUnit.GramSquareMeter: - return FromGramSquareMeters(value.Value); - case MassMomentOfInertiaUnit.GramSquareMillimeter: - return FromGramSquareMillimeters(value.Value); - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: - return FromKilogramSquareCentimeters(value.Value); - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: - return FromKilogramSquareDecimeters(value.Value); - case MassMomentOfInertiaUnit.KilogramSquareMeter: - return FromKilogramSquareMeters(value.Value); - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: - return FromKilogramSquareMillimeters(value.Value); - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: - return FromKilotonneSquareCentimeters(value.Value); - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: - return FromKilotonneSquareDecimeters(value.Value); - case MassMomentOfInertiaUnit.KilotonneSquareMeter: - return FromKilotonneSquareMeters(value.Value); - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: - return FromKilotonneSquareMilimeters(value.Value); - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: - return FromMegatonneSquareCentimeters(value.Value); - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: - return FromMegatonneSquareDecimeters(value.Value); - case MassMomentOfInertiaUnit.MegatonneSquareMeter: - return FromMegatonneSquareMeters(value.Value); - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: - return FromMegatonneSquareMilimeters(value.Value); - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: - return FromMilligramSquareCentimeters(value.Value); - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: - return FromMilligramSquareDecimeters(value.Value); - case MassMomentOfInertiaUnit.MilligramSquareMeter: - return FromMilligramSquareMeters(value.Value); - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: - return FromMilligramSquareMillimeters(value.Value); - case MassMomentOfInertiaUnit.PoundSquareFoot: - return FromPoundSquareFeet(value.Value); - case MassMomentOfInertiaUnit.PoundSquareInch: - return FromPoundSquareInches(value.Value); - case MassMomentOfInertiaUnit.TonneSquareCentimeter: - return FromTonneSquareCentimeters(value.Value); - case MassMomentOfInertiaUnit.TonneSquareDecimeter: - return FromTonneSquareDecimeters(value.Value); - case MassMomentOfInertiaUnit.TonneSquareMeter: - return FromTonneSquareMeters(value.Value); - case MassMomentOfInertiaUnit.TonneSquareMilimeter: - return FromTonneSquareMilimeters(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MassMomentOfInertia((double)value.Value, fromUnit); } #endif @@ -1372,12 +1082,29 @@ public static string GetAbbreviation(MassMomentOfInertiaUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MassMomentOfInertiaUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MassMomentOfInertiaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1388,37 +1115,37 @@ public static string GetAbbreviation(MassMomentOfInertiaUnit unit, [CanBeNull] C #if !WINDOWS_UWP public static MassMomentOfInertia operator -(MassMomentOfInertia right) { - return new MassMomentOfInertia(-right._kilogramSquareMeters); + return new MassMomentOfInertia(-right.Value, right.Unit); } public static MassMomentOfInertia operator +(MassMomentOfInertia left, MassMomentOfInertia right) { - return new MassMomentOfInertia(left._kilogramSquareMeters + right._kilogramSquareMeters); + return new MassMomentOfInertia(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static MassMomentOfInertia operator -(MassMomentOfInertia left, MassMomentOfInertia right) { - return new MassMomentOfInertia(left._kilogramSquareMeters - right._kilogramSquareMeters); + return new MassMomentOfInertia(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static MassMomentOfInertia operator *(double left, MassMomentOfInertia right) { - return new MassMomentOfInertia(left*right._kilogramSquareMeters); + return new MassMomentOfInertia(left * right.Value, right.Unit); } public static MassMomentOfInertia operator *(MassMomentOfInertia left, double right) { - return new MassMomentOfInertia(left._kilogramSquareMeters*(double)right); + return new MassMomentOfInertia(left.Value * right, left.Unit); } public static MassMomentOfInertia operator /(MassMomentOfInertia left, double right) { - return new MassMomentOfInertia(left._kilogramSquareMeters/(double)right); + return new MassMomentOfInertia(left.Value / right, left.Unit); } public static double operator /(MassMomentOfInertia left, MassMomentOfInertia right) { - return Convert.ToDouble(left._kilogramSquareMeters/right._kilogramSquareMeters); + return left.KilogramSquareMeters / right.KilogramSquareMeters; } #endif @@ -1441,43 +1168,43 @@ public int CompareTo(object obj) #endif int CompareTo(MassMomentOfInertia other) { - return _kilogramSquareMeters.CompareTo(other._kilogramSquareMeters); + return AsBaseUnitKilogramSquareMeters().CompareTo(other.AsBaseUnitKilogramSquareMeters()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(MassMomentOfInertia left, MassMomentOfInertia right) { - return left._kilogramSquareMeters <= right._kilogramSquareMeters; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(MassMomentOfInertia left, MassMomentOfInertia right) { - return left._kilogramSquareMeters >= right._kilogramSquareMeters; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(MassMomentOfInertia left, MassMomentOfInertia right) { - return left._kilogramSquareMeters < right._kilogramSquareMeters; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(MassMomentOfInertia left, MassMomentOfInertia right) { - return left._kilogramSquareMeters > right._kilogramSquareMeters; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(MassMomentOfInertia left, MassMomentOfInertia right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramSquareMeters == right._kilogramSquareMeters; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(MassMomentOfInertia left, MassMomentOfInertia right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramSquareMeters != right._kilogramSquareMeters; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1489,7 +1216,7 @@ public override bool Equals(object obj) return false; } - return _kilogramSquareMeters.Equals(((MassMomentOfInertia) obj)._kilogramSquareMeters); + return AsBaseUnitKilogramSquareMeters().Equals(((MassMomentOfInertia) obj).AsBaseUnitKilogramSquareMeters()); } /// @@ -1502,12 +1229,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(MassMomentOfInertia other, MassMomentOfInertia maxError) { - return Math.Abs(_kilogramSquareMeters - other._kilogramSquareMeters) <= maxError._kilogramSquareMeters; + return Math.Abs(AsBaseUnitKilogramSquareMeters() - other.AsBaseUnitKilogramSquareMeters()) <= maxError.AsBaseUnitKilogramSquareMeters(); } public override int GetHashCode() { - return _kilogramSquareMeters.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1517,64 +1244,44 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MassMomentOfInertiaUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitKilogramSquareMeters(); + switch (unit) { - case MassMomentOfInertiaUnit.GramSquareCentimeter: - return GramSquareCentimeters; - case MassMomentOfInertiaUnit.GramSquareDecimeter: - return GramSquareDecimeters; - case MassMomentOfInertiaUnit.GramSquareMeter: - return GramSquareMeters; - case MassMomentOfInertiaUnit.GramSquareMillimeter: - return GramSquareMillimeters; - case MassMomentOfInertiaUnit.KilogramSquareCentimeter: - return KilogramSquareCentimeters; - case MassMomentOfInertiaUnit.KilogramSquareDecimeter: - return KilogramSquareDecimeters; - case MassMomentOfInertiaUnit.KilogramSquareMeter: - return KilogramSquareMeters; - case MassMomentOfInertiaUnit.KilogramSquareMillimeter: - return KilogramSquareMillimeters; - case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: - return KilotonneSquareCentimeters; - case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: - return KilotonneSquareDecimeters; - case MassMomentOfInertiaUnit.KilotonneSquareMeter: - return KilotonneSquareMeters; - case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: - return KilotonneSquareMilimeters; - case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: - return MegatonneSquareCentimeters; - case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: - return MegatonneSquareDecimeters; - case MassMomentOfInertiaUnit.MegatonneSquareMeter: - return MegatonneSquareMeters; - case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: - return MegatonneSquareMilimeters; - case MassMomentOfInertiaUnit.MilligramSquareCentimeter: - return MilligramSquareCentimeters; - case MassMomentOfInertiaUnit.MilligramSquareDecimeter: - return MilligramSquareDecimeters; - case MassMomentOfInertiaUnit.MilligramSquareMeter: - return MilligramSquareMeters; - case MassMomentOfInertiaUnit.MilligramSquareMillimeter: - return MilligramSquareMillimeters; - case MassMomentOfInertiaUnit.PoundSquareFoot: - return PoundSquareFeet; - case MassMomentOfInertiaUnit.PoundSquareInch: - return PoundSquareInches; - case MassMomentOfInertiaUnit.TonneSquareCentimeter: - return TonneSquareCentimeters; - case MassMomentOfInertiaUnit.TonneSquareDecimeter: - return TonneSquareDecimeters; - case MassMomentOfInertiaUnit.TonneSquareMeter: - return TonneSquareMeters; - case MassMomentOfInertiaUnit.TonneSquareMilimeter: - return TonneSquareMilimeters; + case MassMomentOfInertiaUnit.GramSquareCentimeter: return baseUnitValue*1e7; + case MassMomentOfInertiaUnit.GramSquareDecimeter: return baseUnitValue*1e5; + case MassMomentOfInertiaUnit.GramSquareMeter: return baseUnitValue*1e3; + case MassMomentOfInertiaUnit.GramSquareMillimeter: return baseUnitValue*1e9; + case MassMomentOfInertiaUnit.KilogramSquareCentimeter: return (baseUnitValue*1e7) / 1e3d; + case MassMomentOfInertiaUnit.KilogramSquareDecimeter: return (baseUnitValue*1e5) / 1e3d; + case MassMomentOfInertiaUnit.KilogramSquareMeter: return (baseUnitValue*1e3) / 1e3d; + case MassMomentOfInertiaUnit.KilogramSquareMillimeter: return (baseUnitValue*1e9) / 1e3d; + case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: return (baseUnitValue*1e1) / 1e3d; + case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: return (baseUnitValue*1e-1) / 1e3d; + case MassMomentOfInertiaUnit.KilotonneSquareMeter: return (baseUnitValue*1e-3) / 1e3d; + case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: return (baseUnitValue*1e3) / 1e3d; + case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: return (baseUnitValue*1e1) / 1e6d; + case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: return (baseUnitValue*1e-1) / 1e6d; + case MassMomentOfInertiaUnit.MegatonneSquareMeter: return (baseUnitValue*1e-3) / 1e6d; + case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: return (baseUnitValue*1e3) / 1e6d; + case MassMomentOfInertiaUnit.MilligramSquareCentimeter: return (baseUnitValue*1e7) / 1e-3d; + case MassMomentOfInertiaUnit.MilligramSquareDecimeter: return (baseUnitValue*1e5) / 1e-3d; + case MassMomentOfInertiaUnit.MilligramSquareMeter: return (baseUnitValue*1e3) / 1e-3d; + case MassMomentOfInertiaUnit.MilligramSquareMillimeter: return (baseUnitValue*1e9) / 1e-3d; + case MassMomentOfInertiaUnit.PoundSquareFoot: return baseUnitValue/4.21401101e-2; + case MassMomentOfInertiaUnit.PoundSquareInch: return baseUnitValue/2.9263965e-4; + case MassMomentOfInertiaUnit.TonneSquareCentimeter: return baseUnitValue*1e1; + case MassMomentOfInertiaUnit.TonneSquareDecimeter: return baseUnitValue*1e-1; + case MassMomentOfInertiaUnit.TonneSquareMeter: return baseUnitValue*1e-3; + case MassMomentOfInertiaUnit.TonneSquareMilimeter: return baseUnitValue*1e3; default: throw new NotImplementedException("unit: " + unit); @@ -1616,7 +1323,11 @@ public static MassMomentOfInertia Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1635,17 +1346,24 @@ public static MassMomentOfInertia Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MassMomentOfInertia Parse(string str, [CanBeNull] Culture culture) + public static MassMomentOfInertia Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1671,16 +1389,41 @@ public static bool TryParse([CanBeNull] string str, out MassMomentOfInertia resu /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out MassMomentOfInertia result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out MassMomentOfInertia result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1693,6 +1436,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1706,11 +1450,14 @@ public static MassMomentOfInertiaUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MassMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1719,6 +1466,8 @@ public static MassMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string c /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1731,18 +1480,18 @@ public static MassMomentOfInertiaUnit ParseUnit(string str, [CanBeNull] string c #else public #endif - static MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MassMomentOfInertiaUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MassMomentOfInertiaUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1751,6 +1500,7 @@ static MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider formatProvi #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is KilogramSquareMeter /// @@ -1762,7 +1512,7 @@ static MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider formatProvi /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1779,74 +1529,154 @@ public string ToString(MassMomentOfInertiaUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MassMomentOfInertiaUnit unit, [CanBeNull] Culture culture) + public string ToString( + MassMomentOfInertiaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MassMomentOfInertiaUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MassMomentOfInertiaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MassMomentOfInertiaUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MassMomentOfInertiaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of MassMomentOfInertia /// - public static MassMomentOfInertia MaxValue - { - get - { - return new MassMomentOfInertia(double.MaxValue); - } - } + public static MassMomentOfInertia MaxValue => new MassMomentOfInertia(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of MassMomentOfInertia /// - public static MassMomentOfInertia MinValue + public static MassMomentOfInertia MinValue => new MassMomentOfInertia(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitKilogramSquareMeters() { - get + if (Unit == MassMomentOfInertiaUnit.KilogramSquareMeter) { return _value; } + + switch (Unit) { - return new MassMomentOfInertia(double.MinValue); - } - } - } + case MassMomentOfInertiaUnit.GramSquareCentimeter: return _value/1e7; + case MassMomentOfInertiaUnit.GramSquareDecimeter: return _value/1e5; + case MassMomentOfInertiaUnit.GramSquareMeter: return _value/1e3; + case MassMomentOfInertiaUnit.GramSquareMillimeter: return _value/1e9; + case MassMomentOfInertiaUnit.KilogramSquareCentimeter: return (_value/1e7) * 1e3d; + case MassMomentOfInertiaUnit.KilogramSquareDecimeter: return (_value/1e5) * 1e3d; + case MassMomentOfInertiaUnit.KilogramSquareMeter: return (_value/1e3) * 1e3d; + case MassMomentOfInertiaUnit.KilogramSquareMillimeter: return (_value/1e9) * 1e3d; + case MassMomentOfInertiaUnit.KilotonneSquareCentimeter: return (_value/1e1) * 1e3d; + case MassMomentOfInertiaUnit.KilotonneSquareDecimeter: return (_value/1e-1) * 1e3d; + case MassMomentOfInertiaUnit.KilotonneSquareMeter: return (_value/1e-3) * 1e3d; + case MassMomentOfInertiaUnit.KilotonneSquareMilimeter: return (_value/1e3) * 1e3d; + case MassMomentOfInertiaUnit.MegatonneSquareCentimeter: return (_value/1e1) * 1e6d; + case MassMomentOfInertiaUnit.MegatonneSquareDecimeter: return (_value/1e-1) * 1e6d; + case MassMomentOfInertiaUnit.MegatonneSquareMeter: return (_value/1e-3) * 1e6d; + case MassMomentOfInertiaUnit.MegatonneSquareMilimeter: return (_value/1e3) * 1e6d; + case MassMomentOfInertiaUnit.MilligramSquareCentimeter: return (_value/1e7) * 1e-3d; + case MassMomentOfInertiaUnit.MilligramSquareDecimeter: return (_value/1e5) * 1e-3d; + case MassMomentOfInertiaUnit.MilligramSquareMeter: return (_value/1e3) * 1e-3d; + case MassMomentOfInertiaUnit.MilligramSquareMillimeter: return (_value/1e9) * 1e-3d; + case MassMomentOfInertiaUnit.PoundSquareFoot: return _value*4.21401101e-2; + case MassMomentOfInertiaUnit.PoundSquareInch: return _value*2.9263965e-4; + case MassMomentOfInertiaUnit.TonneSquareCentimeter: return _value/1e1; + case MassMomentOfInertiaUnit.TonneSquareDecimeter: return _value/1e-1; + case MassMomentOfInertiaUnit.TonneSquareMeter: return _value/1e-3; + case MassMomentOfInertiaUnit.TonneSquareMilimeter: return _value/1e3; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MassMomentOfInertiaUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs index 56216805d1..bc5f84a399 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct MolarEnergy : IComparable, IComparable #endif { /// - /// Base unit of MolarEnergy. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarEnergyUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _joulesPerMole; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public MolarEnergy() : this(0) + public MolarEnergy() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public MolarEnergy(double joulespermole) { - _joulesPerMole = Convert.ToDouble(joulespermole); + _value = Convert.ToDouble(joulespermole); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + MolarEnergy(double numericValue, MolarEnergyUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit JoulePerMole. + /// + /// Value assuming base unit JoulePerMole. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MolarEnergy(long joulespermole) - { - _joulesPerMole = Convert.ToDouble(joulespermole); - } + MolarEnergy(long joulespermole) : this(Convert.ToDouble(joulespermole), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit JoulePerMole. + /// + /// Value assuming base unit JoulePerMole. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MolarEnergy(decimal joulespermole) - { - _joulesPerMole = Convert.ToDouble(joulespermole); - } + MolarEnergy(decimal joulespermole) : this(Convert.ToDouble(joulespermole), BaseUnit) { } #region Properties @@ -119,48 +156,30 @@ public MolarEnergy(double joulespermole) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MolarEnergyUnit BaseUnit - { - get { return MolarEnergyUnit.JoulePerMole; } - } + public static MolarEnergyUnit BaseUnit => MolarEnergyUnit.JoulePerMole; /// /// All units of measurement for the MolarEnergy quantity. /// public static MolarEnergyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().ToArray(); - /// /// Get MolarEnergy in JoulesPerMole. /// - public double JoulesPerMole - { - get { return _joulesPerMole; } - } - + public double JoulesPerMole => As(MolarEnergyUnit.JoulePerMole); /// /// Get MolarEnergy in KilojoulesPerMole. /// - public double KilojoulesPerMole - { - get { return (_joulesPerMole) / 1e3d; } - } - + public double KilojoulesPerMole => As(MolarEnergyUnit.KilojoulePerMole); /// /// Get MolarEnergy in MegajoulesPerMole. /// - public double MegajoulesPerMole - { - get { return (_joulesPerMole) / 1e6d; } - } + public double MegajoulesPerMole => As(MolarEnergyUnit.MegajoulePerMole); #endregion #region Static - public static MolarEnergy Zero - { - get { return new MolarEnergy(); } - } + public static MolarEnergy Zero => new MolarEnergy(0, BaseUnit); /// /// Get MolarEnergy from JoulesPerMole. @@ -168,17 +187,13 @@ public static MolarEnergy Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarEnergy FromJoulesPerMole(double joulespermole) - { - double value = (double) joulespermole; - return new MolarEnergy(value); - } #else public static MolarEnergy FromJoulesPerMole(QuantityValue joulespermole) +#endif { double value = (double) joulespermole; - return new MolarEnergy((value)); + return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); } -#endif /// /// Get MolarEnergy from KilojoulesPerMole. @@ -186,17 +201,13 @@ public static MolarEnergy FromJoulesPerMole(QuantityValue joulespermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarEnergy FromKilojoulesPerMole(double kilojoulespermole) - { - double value = (double) kilojoulespermole; - return new MolarEnergy((value) * 1e3d); - } #else public static MolarEnergy FromKilojoulesPerMole(QuantityValue kilojoulespermole) +#endif { double value = (double) kilojoulespermole; - return new MolarEnergy(((value) * 1e3d)); + return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); } -#endif /// /// Get MolarEnergy from MegajoulesPerMole. @@ -204,17 +215,13 @@ public static MolarEnergy FromKilojoulesPerMole(QuantityValue kilojoulespermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarEnergy FromMegajoulesPerMole(double megajoulespermole) - { - double value = (double) megajoulespermole; - return new MolarEnergy((value) * 1e6d); - } #else public static MolarEnergy FromMegajoulesPerMole(QuantityValue megajoulespermole) +#endif { double value = (double) megajoulespermole; - return new MolarEnergy(((value) * 1e6d)); + return new MolarEnergy(value, MolarEnergyUnit.MegajoulePerMole); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -279,18 +286,7 @@ public static MolarEnergy From(double value, MolarEnergyUnit fromUnit) public static MolarEnergy From(QuantityValue value, MolarEnergyUnit fromUnit) #endif { - switch (fromUnit) - { - case MolarEnergyUnit.JoulePerMole: - return FromJoulesPerMole(value); - case MolarEnergyUnit.KilojoulePerMole: - return FromKilojoulesPerMole(value); - case MolarEnergyUnit.MegajoulePerMole: - return FromMegajoulesPerMole(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MolarEnergy((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -307,18 +303,8 @@ public static MolarEnergy From(QuantityValue value, MolarEnergyUnit fromUnit) { return null; } - switch (fromUnit) - { - case MolarEnergyUnit.JoulePerMole: - return FromJoulesPerMole(value.Value); - case MolarEnergyUnit.KilojoulePerMole: - return FromKilojoulesPerMole(value.Value); - case MolarEnergyUnit.MegajoulePerMole: - return FromMegajoulesPerMole(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MolarEnergy((double)value.Value, fromUnit); } #endif @@ -337,12 +323,29 @@ public static string GetAbbreviation(MolarEnergyUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MolarEnergyUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MolarEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -353,37 +356,37 @@ public static string GetAbbreviation(MolarEnergyUnit unit, [CanBeNull] Culture c #if !WINDOWS_UWP public static MolarEnergy operator -(MolarEnergy right) { - return new MolarEnergy(-right._joulesPerMole); + return new MolarEnergy(-right.Value, right.Unit); } public static MolarEnergy operator +(MolarEnergy left, MolarEnergy right) { - return new MolarEnergy(left._joulesPerMole + right._joulesPerMole); + return new MolarEnergy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static MolarEnergy operator -(MolarEnergy left, MolarEnergy right) { - return new MolarEnergy(left._joulesPerMole - right._joulesPerMole); + return new MolarEnergy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static MolarEnergy operator *(double left, MolarEnergy right) { - return new MolarEnergy(left*right._joulesPerMole); + return new MolarEnergy(left * right.Value, right.Unit); } public static MolarEnergy operator *(MolarEnergy left, double right) { - return new MolarEnergy(left._joulesPerMole*(double)right); + return new MolarEnergy(left.Value * right, left.Unit); } public static MolarEnergy operator /(MolarEnergy left, double right) { - return new MolarEnergy(left._joulesPerMole/(double)right); + return new MolarEnergy(left.Value / right, left.Unit); } public static double operator /(MolarEnergy left, MolarEnergy right) { - return Convert.ToDouble(left._joulesPerMole/right._joulesPerMole); + return left.JoulesPerMole / right.JoulesPerMole; } #endif @@ -406,43 +409,43 @@ public int CompareTo(object obj) #endif int CompareTo(MolarEnergy other) { - return _joulesPerMole.CompareTo(other._joulesPerMole); + return AsBaseUnitJoulesPerMole().CompareTo(other.AsBaseUnitJoulesPerMole()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(MolarEnergy left, MolarEnergy right) { - return left._joulesPerMole <= right._joulesPerMole; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(MolarEnergy left, MolarEnergy right) { - return left._joulesPerMole >= right._joulesPerMole; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(MolarEnergy left, MolarEnergy right) { - return left._joulesPerMole < right._joulesPerMole; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(MolarEnergy left, MolarEnergy right) { - return left._joulesPerMole > right._joulesPerMole; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(MolarEnergy left, MolarEnergy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerMole == right._joulesPerMole; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(MolarEnergy left, MolarEnergy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerMole != right._joulesPerMole; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -454,7 +457,7 @@ public override bool Equals(object obj) return false; } - return _joulesPerMole.Equals(((MolarEnergy) obj)._joulesPerMole); + return AsBaseUnitJoulesPerMole().Equals(((MolarEnergy) obj).AsBaseUnitJoulesPerMole()); } /// @@ -467,12 +470,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(MolarEnergy other, MolarEnergy maxError) { - return Math.Abs(_joulesPerMole - other._joulesPerMole) <= maxError._joulesPerMole; + return Math.Abs(AsBaseUnitJoulesPerMole() - other.AsBaseUnitJoulesPerMole()) <= maxError.AsBaseUnitJoulesPerMole(); } public override int GetHashCode() { - return _joulesPerMole.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -482,18 +485,21 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MolarEnergyUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitJoulesPerMole(); + switch (unit) { - case MolarEnergyUnit.JoulePerMole: - return JoulesPerMole; - case MolarEnergyUnit.KilojoulePerMole: - return KilojoulesPerMole; - case MolarEnergyUnit.MegajoulePerMole: - return MegajoulesPerMole; + case MolarEnergyUnit.JoulePerMole: return baseUnitValue; + case MolarEnergyUnit.KilojoulePerMole: return (baseUnitValue) / 1e3d; + case MolarEnergyUnit.MegajoulePerMole: return (baseUnitValue) / 1e6d; default: throw new NotImplementedException("unit: " + unit); @@ -535,7 +541,11 @@ public static MolarEnergy Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -554,17 +564,24 @@ public static MolarEnergy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MolarEnergy Parse(string str, [CanBeNull] Culture culture) + public static MolarEnergy Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -590,16 +607,41 @@ public static bool TryParse([CanBeNull] string str, out MolarEnergy result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out MolarEnergy result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out MolarEnergy result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -612,6 +654,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -625,11 +668,14 @@ public static MolarEnergyUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MolarEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -638,6 +684,8 @@ public static MolarEnergyUnit ParseUnit(string str, [CanBeNull] string cultureNa /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -650,18 +698,18 @@ public static MolarEnergyUnit ParseUnit(string str, [CanBeNull] string cultureNa #else public #endif - static MolarEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MolarEnergyUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MolarEnergyUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarEnergyUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -670,6 +718,7 @@ static MolarEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = nu #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is JoulePerMole /// @@ -681,7 +730,7 @@ static MolarEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = nu /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -698,74 +747,131 @@ public string ToString(MolarEnergyUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MolarEnergyUnit unit, [CanBeNull] Culture culture) + public string ToString( + MolarEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MolarEnergyUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MolarEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MolarEnergyUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MolarEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of MolarEnergy /// - public static MolarEnergy MaxValue - { - get - { - return new MolarEnergy(double.MaxValue); - } - } + public static MolarEnergy MaxValue => new MolarEnergy(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of MolarEnergy /// - public static MolarEnergy MinValue + public static MolarEnergy MinValue => new MolarEnergy(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitJoulesPerMole() { - get + if (Unit == MolarEnergyUnit.JoulePerMole) { return _value; } + + switch (Unit) { - return new MolarEnergy(double.MinValue); - } - } - } + case MolarEnergyUnit.JoulePerMole: return _value; + case MolarEnergyUnit.KilojoulePerMole: return (_value) * 1e3d; + case MolarEnergyUnit.MegajoulePerMole: return (_value) * 1e6d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MolarEnergyUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs index b6fe5a2647..d4cbf59b53 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct MolarEntropy : IComparable, IComparable #endif { /// - /// Base unit of MolarEntropy. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly MolarEntropyUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _joulesPerMoleKelvin; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public MolarEntropy() : this(0) + public MolarEntropy() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public MolarEntropy(double joulespermolekelvin) { - _joulesPerMoleKelvin = Convert.ToDouble(joulespermolekelvin); + _value = Convert.ToDouble(joulespermolekelvin); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + MolarEntropy(double numericValue, MolarEntropyUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit JoulePerMoleKelvin. + /// + /// Value assuming base unit JoulePerMoleKelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MolarEntropy(long joulespermolekelvin) - { - _joulesPerMoleKelvin = Convert.ToDouble(joulespermolekelvin); - } + MolarEntropy(long joulespermolekelvin) : this(Convert.ToDouble(joulespermolekelvin), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit JoulePerMoleKelvin. + /// + /// Value assuming base unit JoulePerMoleKelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MolarEntropy(decimal joulespermolekelvin) - { - _joulesPerMoleKelvin = Convert.ToDouble(joulespermolekelvin); - } + MolarEntropy(decimal joulespermolekelvin) : this(Convert.ToDouble(joulespermolekelvin), BaseUnit) { } #region Properties @@ -119,48 +156,30 @@ public MolarEntropy(double joulespermolekelvin) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MolarEntropyUnit BaseUnit - { - get { return MolarEntropyUnit.JoulePerMoleKelvin; } - } + public static MolarEntropyUnit BaseUnit => MolarEntropyUnit.JoulePerMoleKelvin; /// /// All units of measurement for the MolarEntropy quantity. /// public static MolarEntropyUnit[] Units { get; } = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().ToArray(); - /// /// Get MolarEntropy in JoulesPerMoleKelvin. /// - public double JoulesPerMoleKelvin - { - get { return _joulesPerMoleKelvin; } - } - + public double JoulesPerMoleKelvin => As(MolarEntropyUnit.JoulePerMoleKelvin); /// /// Get MolarEntropy in KilojoulesPerMoleKelvin. /// - public double KilojoulesPerMoleKelvin - { - get { return (_joulesPerMoleKelvin) / 1e3d; } - } - + public double KilojoulesPerMoleKelvin => As(MolarEntropyUnit.KilojoulePerMoleKelvin); /// /// Get MolarEntropy in MegajoulesPerMoleKelvin. /// - public double MegajoulesPerMoleKelvin - { - get { return (_joulesPerMoleKelvin) / 1e6d; } - } + public double MegajoulesPerMoleKelvin => As(MolarEntropyUnit.MegajoulePerMoleKelvin); #endregion #region Static - public static MolarEntropy Zero - { - get { return new MolarEntropy(); } - } + public static MolarEntropy Zero => new MolarEntropy(0, BaseUnit); /// /// Get MolarEntropy from JoulesPerMoleKelvin. @@ -168,17 +187,13 @@ public static MolarEntropy Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarEntropy FromJoulesPerMoleKelvin(double joulespermolekelvin) - { - double value = (double) joulespermolekelvin; - return new MolarEntropy(value); - } #else public static MolarEntropy FromJoulesPerMoleKelvin(QuantityValue joulespermolekelvin) +#endif { double value = (double) joulespermolekelvin; - return new MolarEntropy((value)); + return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); } -#endif /// /// Get MolarEntropy from KilojoulesPerMoleKelvin. @@ -186,17 +201,13 @@ public static MolarEntropy FromJoulesPerMoleKelvin(QuantityValue joulespermoleke #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarEntropy FromKilojoulesPerMoleKelvin(double kilojoulespermolekelvin) - { - double value = (double) kilojoulespermolekelvin; - return new MolarEntropy((value) * 1e3d); - } #else public static MolarEntropy FromKilojoulesPerMoleKelvin(QuantityValue kilojoulespermolekelvin) +#endif { double value = (double) kilojoulespermolekelvin; - return new MolarEntropy(((value) * 1e3d)); + return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); } -#endif /// /// Get MolarEntropy from MegajoulesPerMoleKelvin. @@ -204,17 +215,13 @@ public static MolarEntropy FromKilojoulesPerMoleKelvin(QuantityValue kilojoulesp #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarEntropy FromMegajoulesPerMoleKelvin(double megajoulespermolekelvin) - { - double value = (double) megajoulespermolekelvin; - return new MolarEntropy((value) * 1e6d); - } #else public static MolarEntropy FromMegajoulesPerMoleKelvin(QuantityValue megajoulespermolekelvin) +#endif { double value = (double) megajoulespermolekelvin; - return new MolarEntropy(((value) * 1e6d)); + return new MolarEntropy(value, MolarEntropyUnit.MegajoulePerMoleKelvin); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -279,18 +286,7 @@ public static MolarEntropy From(double value, MolarEntropyUnit fromUnit) public static MolarEntropy From(QuantityValue value, MolarEntropyUnit fromUnit) #endif { - switch (fromUnit) - { - case MolarEntropyUnit.JoulePerMoleKelvin: - return FromJoulesPerMoleKelvin(value); - case MolarEntropyUnit.KilojoulePerMoleKelvin: - return FromKilojoulesPerMoleKelvin(value); - case MolarEntropyUnit.MegajoulePerMoleKelvin: - return FromMegajoulesPerMoleKelvin(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MolarEntropy((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -307,18 +303,8 @@ public static MolarEntropy From(QuantityValue value, MolarEntropyUnit fromUnit) { return null; } - switch (fromUnit) - { - case MolarEntropyUnit.JoulePerMoleKelvin: - return FromJoulesPerMoleKelvin(value.Value); - case MolarEntropyUnit.KilojoulePerMoleKelvin: - return FromKilojoulesPerMoleKelvin(value.Value); - case MolarEntropyUnit.MegajoulePerMoleKelvin: - return FromMegajoulesPerMoleKelvin(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MolarEntropy((double)value.Value, fromUnit); } #endif @@ -337,12 +323,29 @@ public static string GetAbbreviation(MolarEntropyUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MolarEntropyUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MolarEntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -353,37 +356,37 @@ public static string GetAbbreviation(MolarEntropyUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static MolarEntropy operator -(MolarEntropy right) { - return new MolarEntropy(-right._joulesPerMoleKelvin); + return new MolarEntropy(-right.Value, right.Unit); } public static MolarEntropy operator +(MolarEntropy left, MolarEntropy right) { - return new MolarEntropy(left._joulesPerMoleKelvin + right._joulesPerMoleKelvin); + return new MolarEntropy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static MolarEntropy operator -(MolarEntropy left, MolarEntropy right) { - return new MolarEntropy(left._joulesPerMoleKelvin - right._joulesPerMoleKelvin); + return new MolarEntropy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static MolarEntropy operator *(double left, MolarEntropy right) { - return new MolarEntropy(left*right._joulesPerMoleKelvin); + return new MolarEntropy(left * right.Value, right.Unit); } public static MolarEntropy operator *(MolarEntropy left, double right) { - return new MolarEntropy(left._joulesPerMoleKelvin*(double)right); + return new MolarEntropy(left.Value * right, left.Unit); } public static MolarEntropy operator /(MolarEntropy left, double right) { - return new MolarEntropy(left._joulesPerMoleKelvin/(double)right); + return new MolarEntropy(left.Value / right, left.Unit); } public static double operator /(MolarEntropy left, MolarEntropy right) { - return Convert.ToDouble(left._joulesPerMoleKelvin/right._joulesPerMoleKelvin); + return left.JoulesPerMoleKelvin / right.JoulesPerMoleKelvin; } #endif @@ -406,43 +409,43 @@ public int CompareTo(object obj) #endif int CompareTo(MolarEntropy other) { - return _joulesPerMoleKelvin.CompareTo(other._joulesPerMoleKelvin); + return AsBaseUnitJoulesPerMoleKelvin().CompareTo(other.AsBaseUnitJoulesPerMoleKelvin()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(MolarEntropy left, MolarEntropy right) { - return left._joulesPerMoleKelvin <= right._joulesPerMoleKelvin; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(MolarEntropy left, MolarEntropy right) { - return left._joulesPerMoleKelvin >= right._joulesPerMoleKelvin; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(MolarEntropy left, MolarEntropy right) { - return left._joulesPerMoleKelvin < right._joulesPerMoleKelvin; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(MolarEntropy left, MolarEntropy right) { - return left._joulesPerMoleKelvin > right._joulesPerMoleKelvin; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(MolarEntropy left, MolarEntropy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerMoleKelvin == right._joulesPerMoleKelvin; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(MolarEntropy left, MolarEntropy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerMoleKelvin != right._joulesPerMoleKelvin; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -454,7 +457,7 @@ public override bool Equals(object obj) return false; } - return _joulesPerMoleKelvin.Equals(((MolarEntropy) obj)._joulesPerMoleKelvin); + return AsBaseUnitJoulesPerMoleKelvin().Equals(((MolarEntropy) obj).AsBaseUnitJoulesPerMoleKelvin()); } /// @@ -467,12 +470,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(MolarEntropy other, MolarEntropy maxError) { - return Math.Abs(_joulesPerMoleKelvin - other._joulesPerMoleKelvin) <= maxError._joulesPerMoleKelvin; + return Math.Abs(AsBaseUnitJoulesPerMoleKelvin() - other.AsBaseUnitJoulesPerMoleKelvin()) <= maxError.AsBaseUnitJoulesPerMoleKelvin(); } public override int GetHashCode() { - return _joulesPerMoleKelvin.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -482,18 +485,21 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MolarEntropyUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitJoulesPerMoleKelvin(); + switch (unit) { - case MolarEntropyUnit.JoulePerMoleKelvin: - return JoulesPerMoleKelvin; - case MolarEntropyUnit.KilojoulePerMoleKelvin: - return KilojoulesPerMoleKelvin; - case MolarEntropyUnit.MegajoulePerMoleKelvin: - return MegajoulesPerMoleKelvin; + case MolarEntropyUnit.JoulePerMoleKelvin: return baseUnitValue; + case MolarEntropyUnit.KilojoulePerMoleKelvin: return (baseUnitValue) / 1e3d; + case MolarEntropyUnit.MegajoulePerMoleKelvin: return (baseUnitValue) / 1e6d; default: throw new NotImplementedException("unit: " + unit); @@ -535,7 +541,11 @@ public static MolarEntropy Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -554,17 +564,24 @@ public static MolarEntropy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MolarEntropy Parse(string str, [CanBeNull] Culture culture) + public static MolarEntropy Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -590,16 +607,41 @@ public static bool TryParse([CanBeNull] string str, out MolarEntropy result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out MolarEntropy result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out MolarEntropy result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -612,6 +654,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -625,11 +668,14 @@ public static MolarEntropyUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MolarEntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -638,6 +684,8 @@ public static MolarEntropyUnit ParseUnit(string str, [CanBeNull] string cultureN /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -650,18 +698,18 @@ public static MolarEntropyUnit ParseUnit(string str, [CanBeNull] string cultureN #else public #endif - static MolarEntropyUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MolarEntropyUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MolarEntropyUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarEntropyUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -670,6 +718,7 @@ static MolarEntropyUnit ParseUnit(string str, IFormatProvider formatProvider = n #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is JoulePerMoleKelvin /// @@ -681,7 +730,7 @@ static MolarEntropyUnit ParseUnit(string str, IFormatProvider formatProvider = n /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -698,74 +747,131 @@ public string ToString(MolarEntropyUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MolarEntropyUnit unit, [CanBeNull] Culture culture) + public string ToString( + MolarEntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MolarEntropyUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MolarEntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MolarEntropyUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MolarEntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of MolarEntropy /// - public static MolarEntropy MaxValue - { - get - { - return new MolarEntropy(double.MaxValue); - } - } + public static MolarEntropy MaxValue => new MolarEntropy(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of MolarEntropy /// - public static MolarEntropy MinValue + public static MolarEntropy MinValue => new MolarEntropy(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitJoulesPerMoleKelvin() { - get + if (Unit == MolarEntropyUnit.JoulePerMoleKelvin) { return _value; } + + switch (Unit) { - return new MolarEntropy(double.MinValue); - } - } - } + case MolarEntropyUnit.JoulePerMoleKelvin: return _value; + case MolarEntropyUnit.KilojoulePerMoleKelvin: return (_value) * 1e3d; + case MolarEntropyUnit.MegajoulePerMoleKelvin: return (_value) * 1e6d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MolarEntropyUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs index 8e4524ac1e..72b24f2121 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct MolarMass : IComparable, IComparable #endif { /// - /// Base unit of MolarMass. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _kilogramsPerMole; + private readonly MolarMassUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public MolarMass() : this(0) + public MolarMass() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public MolarMass(double kilogramspermole) { - _kilogramsPerMole = Convert.ToDouble(kilogramspermole); + _value = Convert.ToDouble(kilogramspermole); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + MolarMass(double numericValue, MolarMassUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerMole. + /// + /// Value assuming base unit KilogramPerMole. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MolarMass(long kilogramspermole) - { - _kilogramsPerMole = Convert.ToDouble(kilogramspermole); - } + MolarMass(long kilogramspermole) : this(Convert.ToDouble(kilogramspermole), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit KilogramPerMole. + /// + /// Value assuming base unit KilogramPerMole. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - MolarMass(decimal kilogramspermole) - { - _kilogramsPerMole = Convert.ToDouble(kilogramspermole); - } + MolarMass(decimal kilogramspermole) : this(Convert.ToDouble(kilogramspermole), BaseUnit) { } #region Properties @@ -119,120 +156,66 @@ public MolarMass(double kilogramspermole) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MolarMassUnit BaseUnit - { - get { return MolarMassUnit.KilogramPerMole; } - } + public static MolarMassUnit BaseUnit => MolarMassUnit.KilogramPerMole; /// /// All units of measurement for the MolarMass quantity. /// public static MolarMassUnit[] Units { get; } = Enum.GetValues(typeof(MolarMassUnit)).Cast().ToArray(); - /// /// Get MolarMass in CentigramsPerMole. /// - public double CentigramsPerMole - { - get { return (_kilogramsPerMole*1e3) / 1e-2d; } - } - + public double CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); /// /// Get MolarMass in DecagramsPerMole. /// - public double DecagramsPerMole - { - get { return (_kilogramsPerMole*1e3) / 1e1d; } - } - + public double DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); /// /// Get MolarMass in DecigramsPerMole. /// - public double DecigramsPerMole - { - get { return (_kilogramsPerMole*1e3) / 1e-1d; } - } - + public double DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); /// /// Get MolarMass in GramsPerMole. /// - public double GramsPerMole - { - get { return _kilogramsPerMole*1e3; } - } - + public double GramsPerMole => As(MolarMassUnit.GramPerMole); /// /// Get MolarMass in HectogramsPerMole. /// - public double HectogramsPerMole - { - get { return (_kilogramsPerMole*1e3) / 1e2d; } - } - + public double HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); /// /// Get MolarMass in KilogramsPerMole. /// - public double KilogramsPerMole - { - get { return (_kilogramsPerMole*1e3) / 1e3d; } - } - + public double KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); /// /// Get MolarMass in KilopoundsPerMole. /// - public double KilopoundsPerMole - { - get { return (_kilogramsPerMole/0.45359237) / 1e3d; } - } - + public double KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); /// /// Get MolarMass in MegapoundsPerMole. /// - public double MegapoundsPerMole - { - get { return (_kilogramsPerMole/0.45359237) / 1e6d; } - } - + public double MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); /// /// Get MolarMass in MicrogramsPerMole. /// - public double MicrogramsPerMole - { - get { return (_kilogramsPerMole*1e3) / 1e-6d; } - } - + public double MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); /// /// Get MolarMass in MilligramsPerMole. /// - public double MilligramsPerMole - { - get { return (_kilogramsPerMole*1e3) / 1e-3d; } - } - + public double MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); /// /// Get MolarMass in NanogramsPerMole. /// - public double NanogramsPerMole - { - get { return (_kilogramsPerMole*1e3) / 1e-9d; } - } - + public double NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); /// /// Get MolarMass in PoundsPerMole. /// - public double PoundsPerMole - { - get { return _kilogramsPerMole/0.45359237; } - } + public double PoundsPerMole => As(MolarMassUnit.PoundPerMole); #endregion #region Static - public static MolarMass Zero - { - get { return new MolarMass(); } - } + public static MolarMass Zero => new MolarMass(0, BaseUnit); /// /// Get MolarMass from CentigramsPerMole. @@ -240,17 +223,13 @@ public static MolarMass Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromCentigramsPerMole(double centigramspermole) - { - double value = (double) centigramspermole; - return new MolarMass((value/1e3) * 1e-2d); - } #else public static MolarMass FromCentigramsPerMole(QuantityValue centigramspermole) +#endif { double value = (double) centigramspermole; - return new MolarMass(((value/1e3) * 1e-2d)); + return new MolarMass(value, MolarMassUnit.CentigramPerMole); } -#endif /// /// Get MolarMass from DecagramsPerMole. @@ -258,17 +237,13 @@ public static MolarMass FromCentigramsPerMole(QuantityValue centigramspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromDecagramsPerMole(double decagramspermole) - { - double value = (double) decagramspermole; - return new MolarMass((value/1e3) * 1e1d); - } #else public static MolarMass FromDecagramsPerMole(QuantityValue decagramspermole) +#endif { double value = (double) decagramspermole; - return new MolarMass(((value/1e3) * 1e1d)); + return new MolarMass(value, MolarMassUnit.DecagramPerMole); } -#endif /// /// Get MolarMass from DecigramsPerMole. @@ -276,17 +251,13 @@ public static MolarMass FromDecagramsPerMole(QuantityValue decagramspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromDecigramsPerMole(double decigramspermole) - { - double value = (double) decigramspermole; - return new MolarMass((value/1e3) * 1e-1d); - } #else public static MolarMass FromDecigramsPerMole(QuantityValue decigramspermole) +#endif { double value = (double) decigramspermole; - return new MolarMass(((value/1e3) * 1e-1d)); + return new MolarMass(value, MolarMassUnit.DecigramPerMole); } -#endif /// /// Get MolarMass from GramsPerMole. @@ -294,17 +265,13 @@ public static MolarMass FromDecigramsPerMole(QuantityValue decigramspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromGramsPerMole(double gramspermole) - { - double value = (double) gramspermole; - return new MolarMass(value/1e3); - } #else public static MolarMass FromGramsPerMole(QuantityValue gramspermole) +#endif { double value = (double) gramspermole; - return new MolarMass((value/1e3)); + return new MolarMass(value, MolarMassUnit.GramPerMole); } -#endif /// /// Get MolarMass from HectogramsPerMole. @@ -312,17 +279,13 @@ public static MolarMass FromGramsPerMole(QuantityValue gramspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromHectogramsPerMole(double hectogramspermole) - { - double value = (double) hectogramspermole; - return new MolarMass((value/1e3) * 1e2d); - } #else public static MolarMass FromHectogramsPerMole(QuantityValue hectogramspermole) +#endif { double value = (double) hectogramspermole; - return new MolarMass(((value/1e3) * 1e2d)); + return new MolarMass(value, MolarMassUnit.HectogramPerMole); } -#endif /// /// Get MolarMass from KilogramsPerMole. @@ -330,17 +293,13 @@ public static MolarMass FromHectogramsPerMole(QuantityValue hectogramspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromKilogramsPerMole(double kilogramspermole) - { - double value = (double) kilogramspermole; - return new MolarMass((value/1e3) * 1e3d); - } #else public static MolarMass FromKilogramsPerMole(QuantityValue kilogramspermole) +#endif { double value = (double) kilogramspermole; - return new MolarMass(((value/1e3) * 1e3d)); + return new MolarMass(value, MolarMassUnit.KilogramPerMole); } -#endif /// /// Get MolarMass from KilopoundsPerMole. @@ -348,17 +307,13 @@ public static MolarMass FromKilogramsPerMole(QuantityValue kilogramspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromKilopoundsPerMole(double kilopoundspermole) - { - double value = (double) kilopoundspermole; - return new MolarMass((value*0.45359237) * 1e3d); - } #else public static MolarMass FromKilopoundsPerMole(QuantityValue kilopoundspermole) +#endif { double value = (double) kilopoundspermole; - return new MolarMass(((value*0.45359237) * 1e3d)); + return new MolarMass(value, MolarMassUnit.KilopoundPerMole); } -#endif /// /// Get MolarMass from MegapoundsPerMole. @@ -366,17 +321,13 @@ public static MolarMass FromKilopoundsPerMole(QuantityValue kilopoundspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromMegapoundsPerMole(double megapoundspermole) - { - double value = (double) megapoundspermole; - return new MolarMass((value*0.45359237) * 1e6d); - } #else public static MolarMass FromMegapoundsPerMole(QuantityValue megapoundspermole) +#endif { double value = (double) megapoundspermole; - return new MolarMass(((value*0.45359237) * 1e6d)); + return new MolarMass(value, MolarMassUnit.MegapoundPerMole); } -#endif /// /// Get MolarMass from MicrogramsPerMole. @@ -384,17 +335,13 @@ public static MolarMass FromMegapoundsPerMole(QuantityValue megapoundspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromMicrogramsPerMole(double microgramspermole) - { - double value = (double) microgramspermole; - return new MolarMass((value/1e3) * 1e-6d); - } #else public static MolarMass FromMicrogramsPerMole(QuantityValue microgramspermole) +#endif { double value = (double) microgramspermole; - return new MolarMass(((value/1e3) * 1e-6d)); + return new MolarMass(value, MolarMassUnit.MicrogramPerMole); } -#endif /// /// Get MolarMass from MilligramsPerMole. @@ -402,17 +349,13 @@ public static MolarMass FromMicrogramsPerMole(QuantityValue microgramspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromMilligramsPerMole(double milligramspermole) - { - double value = (double) milligramspermole; - return new MolarMass((value/1e3) * 1e-3d); - } #else public static MolarMass FromMilligramsPerMole(QuantityValue milligramspermole) +#endif { double value = (double) milligramspermole; - return new MolarMass(((value/1e3) * 1e-3d)); + return new MolarMass(value, MolarMassUnit.MilligramPerMole); } -#endif /// /// Get MolarMass from NanogramsPerMole. @@ -420,17 +363,13 @@ public static MolarMass FromMilligramsPerMole(QuantityValue milligramspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromNanogramsPerMole(double nanogramspermole) - { - double value = (double) nanogramspermole; - return new MolarMass((value/1e3) * 1e-9d); - } #else public static MolarMass FromNanogramsPerMole(QuantityValue nanogramspermole) +#endif { double value = (double) nanogramspermole; - return new MolarMass(((value/1e3) * 1e-9d)); + return new MolarMass(value, MolarMassUnit.NanogramPerMole); } -#endif /// /// Get MolarMass from PoundsPerMole. @@ -438,17 +377,13 @@ public static MolarMass FromNanogramsPerMole(QuantityValue nanogramspermole) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static MolarMass FromPoundsPerMole(double poundspermole) - { - double value = (double) poundspermole; - return new MolarMass(value*0.45359237); - } #else public static MolarMass FromPoundsPerMole(QuantityValue poundspermole) +#endif { double value = (double) poundspermole; - return new MolarMass((value*0.45359237)); + return new MolarMass(value, MolarMassUnit.PoundPerMole); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -648,36 +583,7 @@ public static MolarMass From(double value, MolarMassUnit fromUnit) public static MolarMass From(QuantityValue value, MolarMassUnit fromUnit) #endif { - switch (fromUnit) - { - case MolarMassUnit.CentigramPerMole: - return FromCentigramsPerMole(value); - case MolarMassUnit.DecagramPerMole: - return FromDecagramsPerMole(value); - case MolarMassUnit.DecigramPerMole: - return FromDecigramsPerMole(value); - case MolarMassUnit.GramPerMole: - return FromGramsPerMole(value); - case MolarMassUnit.HectogramPerMole: - return FromHectogramsPerMole(value); - case MolarMassUnit.KilogramPerMole: - return FromKilogramsPerMole(value); - case MolarMassUnit.KilopoundPerMole: - return FromKilopoundsPerMole(value); - case MolarMassUnit.MegapoundPerMole: - return FromMegapoundsPerMole(value); - case MolarMassUnit.MicrogramPerMole: - return FromMicrogramsPerMole(value); - case MolarMassUnit.MilligramPerMole: - return FromMilligramsPerMole(value); - case MolarMassUnit.NanogramPerMole: - return FromNanogramsPerMole(value); - case MolarMassUnit.PoundPerMole: - return FromPoundsPerMole(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MolarMass((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -694,36 +600,8 @@ public static MolarMass From(QuantityValue value, MolarMassUnit fromUnit) { return null; } - switch (fromUnit) - { - case MolarMassUnit.CentigramPerMole: - return FromCentigramsPerMole(value.Value); - case MolarMassUnit.DecagramPerMole: - return FromDecagramsPerMole(value.Value); - case MolarMassUnit.DecigramPerMole: - return FromDecigramsPerMole(value.Value); - case MolarMassUnit.GramPerMole: - return FromGramsPerMole(value.Value); - case MolarMassUnit.HectogramPerMole: - return FromHectogramsPerMole(value.Value); - case MolarMassUnit.KilogramPerMole: - return FromKilogramsPerMole(value.Value); - case MolarMassUnit.KilopoundPerMole: - return FromKilopoundsPerMole(value.Value); - case MolarMassUnit.MegapoundPerMole: - return FromMegapoundsPerMole(value.Value); - case MolarMassUnit.MicrogramPerMole: - return FromMicrogramsPerMole(value.Value); - case MolarMassUnit.MilligramPerMole: - return FromMilligramsPerMole(value.Value); - case MolarMassUnit.NanogramPerMole: - return FromNanogramsPerMole(value.Value); - case MolarMassUnit.PoundPerMole: - return FromPoundsPerMole(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new MolarMass((double)value.Value, fromUnit); } #endif @@ -742,12 +620,29 @@ public static string GetAbbreviation(MolarMassUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MolarMassUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MolarMassUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -758,37 +653,37 @@ public static string GetAbbreviation(MolarMassUnit unit, [CanBeNull] Culture cul #if !WINDOWS_UWP public static MolarMass operator -(MolarMass right) { - return new MolarMass(-right._kilogramsPerMole); + return new MolarMass(-right.Value, right.Unit); } public static MolarMass operator +(MolarMass left, MolarMass right) { - return new MolarMass(left._kilogramsPerMole + right._kilogramsPerMole); + return new MolarMass(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static MolarMass operator -(MolarMass left, MolarMass right) { - return new MolarMass(left._kilogramsPerMole - right._kilogramsPerMole); + return new MolarMass(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static MolarMass operator *(double left, MolarMass right) { - return new MolarMass(left*right._kilogramsPerMole); + return new MolarMass(left * right.Value, right.Unit); } public static MolarMass operator *(MolarMass left, double right) { - return new MolarMass(left._kilogramsPerMole*(double)right); + return new MolarMass(left.Value * right, left.Unit); } public static MolarMass operator /(MolarMass left, double right) { - return new MolarMass(left._kilogramsPerMole/(double)right); + return new MolarMass(left.Value / right, left.Unit); } public static double operator /(MolarMass left, MolarMass right) { - return Convert.ToDouble(left._kilogramsPerMole/right._kilogramsPerMole); + return left.KilogramsPerMole / right.KilogramsPerMole; } #endif @@ -811,43 +706,43 @@ public int CompareTo(object obj) #endif int CompareTo(MolarMass other) { - return _kilogramsPerMole.CompareTo(other._kilogramsPerMole); + return AsBaseUnitKilogramsPerMole().CompareTo(other.AsBaseUnitKilogramsPerMole()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(MolarMass left, MolarMass right) { - return left._kilogramsPerMole <= right._kilogramsPerMole; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(MolarMass left, MolarMass right) { - return left._kilogramsPerMole >= right._kilogramsPerMole; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(MolarMass left, MolarMass right) { - return left._kilogramsPerMole < right._kilogramsPerMole; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(MolarMass left, MolarMass right) { - return left._kilogramsPerMole > right._kilogramsPerMole; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(MolarMass left, MolarMass right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerMole == right._kilogramsPerMole; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(MolarMass left, MolarMass right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kilogramsPerMole != right._kilogramsPerMole; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -859,7 +754,7 @@ public override bool Equals(object obj) return false; } - return _kilogramsPerMole.Equals(((MolarMass) obj)._kilogramsPerMole); + return AsBaseUnitKilogramsPerMole().Equals(((MolarMass) obj).AsBaseUnitKilogramsPerMole()); } /// @@ -872,12 +767,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(MolarMass other, MolarMass maxError) { - return Math.Abs(_kilogramsPerMole - other._kilogramsPerMole) <= maxError._kilogramsPerMole; + return Math.Abs(AsBaseUnitKilogramsPerMole() - other.AsBaseUnitKilogramsPerMole()) <= maxError.AsBaseUnitKilogramsPerMole(); } public override int GetHashCode() { - return _kilogramsPerMole.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -887,36 +782,30 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MolarMassUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitKilogramsPerMole(); + switch (unit) { - case MolarMassUnit.CentigramPerMole: - return CentigramsPerMole; - case MolarMassUnit.DecagramPerMole: - return DecagramsPerMole; - case MolarMassUnit.DecigramPerMole: - return DecigramsPerMole; - case MolarMassUnit.GramPerMole: - return GramsPerMole; - case MolarMassUnit.HectogramPerMole: - return HectogramsPerMole; - case MolarMassUnit.KilogramPerMole: - return KilogramsPerMole; - case MolarMassUnit.KilopoundPerMole: - return KilopoundsPerMole; - case MolarMassUnit.MegapoundPerMole: - return MegapoundsPerMole; - case MolarMassUnit.MicrogramPerMole: - return MicrogramsPerMole; - case MolarMassUnit.MilligramPerMole: - return MilligramsPerMole; - case MolarMassUnit.NanogramPerMole: - return NanogramsPerMole; - case MolarMassUnit.PoundPerMole: - return PoundsPerMole; + case MolarMassUnit.CentigramPerMole: return (baseUnitValue*1e3) / 1e-2d; + case MolarMassUnit.DecagramPerMole: return (baseUnitValue*1e3) / 1e1d; + case MolarMassUnit.DecigramPerMole: return (baseUnitValue*1e3) / 1e-1d; + case MolarMassUnit.GramPerMole: return baseUnitValue*1e3; + case MolarMassUnit.HectogramPerMole: return (baseUnitValue*1e3) / 1e2d; + case MolarMassUnit.KilogramPerMole: return (baseUnitValue*1e3) / 1e3d; + case MolarMassUnit.KilopoundPerMole: return (baseUnitValue/0.45359237) / 1e3d; + case MolarMassUnit.MegapoundPerMole: return (baseUnitValue/0.45359237) / 1e6d; + case MolarMassUnit.MicrogramPerMole: return (baseUnitValue*1e3) / 1e-6d; + case MolarMassUnit.MilligramPerMole: return (baseUnitValue*1e3) / 1e-3d; + case MolarMassUnit.NanogramPerMole: return (baseUnitValue*1e3) / 1e-9d; + case MolarMassUnit.PoundPerMole: return baseUnitValue/0.45359237; default: throw new NotImplementedException("unit: " + unit); @@ -958,7 +847,11 @@ public static MolarMass Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -977,17 +870,24 @@ public static MolarMass Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static MolarMass Parse(string str, [CanBeNull] Culture culture) + public static MolarMass Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1013,16 +913,41 @@ public static bool TryParse([CanBeNull] string str, out MolarMass result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out MolarMass result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out MolarMass result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1035,6 +960,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1048,11 +974,14 @@ public static MolarMassUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MolarMassUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1061,6 +990,8 @@ public static MolarMassUnit ParseUnit(string str, [CanBeNull] string cultureName /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1073,18 +1004,18 @@ public static MolarMassUnit ParseUnit(string str, [CanBeNull] string cultureName #else public #endif - static MolarMassUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MolarMassUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MolarMassUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarMassUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1093,6 +1024,7 @@ static MolarMassUnit ParseUnit(string str, IFormatProvider formatProvider = null #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is KilogramPerMole /// @@ -1104,7 +1036,7 @@ static MolarMassUnit ParseUnit(string str, IFormatProvider formatProvider = null /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1121,74 +1053,140 @@ public string ToString(MolarMassUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MolarMassUnit unit, [CanBeNull] Culture culture) + public string ToString( + MolarMassUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MolarMassUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MolarMassUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MolarMassUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MolarMassUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of MolarMass /// - public static MolarMass MaxValue - { - get - { - return new MolarMass(double.MaxValue); - } - } + public static MolarMass MaxValue => new MolarMass(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of MolarMass /// - public static MolarMass MinValue + public static MolarMass MinValue => new MolarMass(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitKilogramsPerMole() { - get + if (Unit == MolarMassUnit.KilogramPerMole) { return _value; } + + switch (Unit) { - return new MolarMass(double.MinValue); - } - } - } + case MolarMassUnit.CentigramPerMole: return (_value/1e3) * 1e-2d; + case MolarMassUnit.DecagramPerMole: return (_value/1e3) * 1e1d; + case MolarMassUnit.DecigramPerMole: return (_value/1e3) * 1e-1d; + case MolarMassUnit.GramPerMole: return _value/1e3; + case MolarMassUnit.HectogramPerMole: return (_value/1e3) * 1e2d; + case MolarMassUnit.KilogramPerMole: return (_value/1e3) * 1e3d; + case MolarMassUnit.KilopoundPerMole: return (_value*0.45359237) * 1e3d; + case MolarMassUnit.MegapoundPerMole: return (_value*0.45359237) * 1e6d; + case MolarMassUnit.MicrogramPerMole: return (_value/1e3) * 1e-6d; + case MolarMassUnit.MilligramPerMole: return (_value/1e3) * 1e-3d; + case MolarMassUnit.NanogramPerMole: return (_value/1e3) * 1e-9d; + case MolarMassUnit.PoundPerMole: return _value*0.45359237; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MolarMassUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs index 09fcbd4f6c..027abb4ea3 100644 --- a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Molarity : IComparable, IComparable #endif { /// - /// Base unit of Molarity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _molesPerCubicMeter; + private readonly MolarityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Molarity() : this(0) + public Molarity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Molarity(double molespercubicmeter) { - _molesPerCubicMeter = Convert.ToDouble(molespercubicmeter); + _value = Convert.ToDouble(molespercubicmeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Molarity(double numericValue, MolarityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit MolesPerCubicMeter. + /// + /// Value assuming base unit MolesPerCubicMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Molarity(long molespercubicmeter) - { - _molesPerCubicMeter = Convert.ToDouble(molespercubicmeter); - } + Molarity(long molespercubicmeter) : this(Convert.ToDouble(molespercubicmeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit MolesPerCubicMeter. + /// + /// Value assuming base unit MolesPerCubicMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Molarity(decimal molespercubicmeter) - { - _molesPerCubicMeter = Convert.ToDouble(molespercubicmeter); - } + Molarity(decimal molespercubicmeter) : this(Convert.ToDouble(molespercubicmeter), BaseUnit) { } #region Properties @@ -119,88 +156,50 @@ public Molarity(double molespercubicmeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static MolarityUnit BaseUnit - { - get { return MolarityUnit.MolesPerCubicMeter; } - } + public static MolarityUnit BaseUnit => MolarityUnit.MolesPerCubicMeter; /// /// All units of measurement for the Molarity quantity. /// public static MolarityUnit[] Units { get; } = Enum.GetValues(typeof(MolarityUnit)).Cast().ToArray(); - /// /// Get Molarity in CentimolesPerLiter. /// - public double CentimolesPerLiter - { - get { return (_molesPerCubicMeter*1e-3) / 1e-2d; } - } - + public double CentimolesPerLiter => As(MolarityUnit.CentimolesPerLiter); /// /// Get Molarity in DecimolesPerLiter. /// - public double DecimolesPerLiter - { - get { return (_molesPerCubicMeter*1e-3) / 1e-1d; } - } - + public double DecimolesPerLiter => As(MolarityUnit.DecimolesPerLiter); /// /// Get Molarity in MicromolesPerLiter. /// - public double MicromolesPerLiter - { - get { return (_molesPerCubicMeter*1e-3) / 1e-6d; } - } - + public double MicromolesPerLiter => As(MolarityUnit.MicromolesPerLiter); /// /// Get Molarity in MillimolesPerLiter. /// - public double MillimolesPerLiter - { - get { return (_molesPerCubicMeter*1e-3) / 1e-3d; } - } - + public double MillimolesPerLiter => As(MolarityUnit.MillimolesPerLiter); /// /// Get Molarity in MolesPerCubicMeter. /// - public double MolesPerCubicMeter - { - get { return _molesPerCubicMeter; } - } - + public double MolesPerCubicMeter => As(MolarityUnit.MolesPerCubicMeter); /// /// Get Molarity in MolesPerLiter. /// - public double MolesPerLiter - { - get { return _molesPerCubicMeter*1e-3; } - } - + public double MolesPerLiter => As(MolarityUnit.MolesPerLiter); /// /// Get Molarity in NanomolesPerLiter. /// - public double NanomolesPerLiter - { - get { return (_molesPerCubicMeter*1e-3) / 1e-9d; } - } - + public double NanomolesPerLiter => As(MolarityUnit.NanomolesPerLiter); /// /// Get Molarity in PicomolesPerLiter. /// - public double PicomolesPerLiter - { - get { return (_molesPerCubicMeter*1e-3) / 1e-12d; } - } + public double PicomolesPerLiter => As(MolarityUnit.PicomolesPerLiter); #endregion #region Static - public static Molarity Zero - { - get { return new Molarity(); } - } + public static Molarity Zero => new Molarity(0, BaseUnit); /// /// Get Molarity from CentimolesPerLiter. @@ -208,17 +207,13 @@ public static Molarity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Molarity FromCentimolesPerLiter(double centimolesperliter) - { - double value = (double) centimolesperliter; - return new Molarity((value/1e-3) * 1e-2d); - } #else public static Molarity FromCentimolesPerLiter(QuantityValue centimolesperliter) +#endif { double value = (double) centimolesperliter; - return new Molarity(((value/1e-3) * 1e-2d)); + return new Molarity(value, MolarityUnit.CentimolesPerLiter); } -#endif /// /// Get Molarity from DecimolesPerLiter. @@ -226,17 +221,13 @@ public static Molarity FromCentimolesPerLiter(QuantityValue centimolesperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Molarity FromDecimolesPerLiter(double decimolesperliter) - { - double value = (double) decimolesperliter; - return new Molarity((value/1e-3) * 1e-1d); - } #else public static Molarity FromDecimolesPerLiter(QuantityValue decimolesperliter) +#endif { double value = (double) decimolesperliter; - return new Molarity(((value/1e-3) * 1e-1d)); + return new Molarity(value, MolarityUnit.DecimolesPerLiter); } -#endif /// /// Get Molarity from MicromolesPerLiter. @@ -244,17 +235,13 @@ public static Molarity FromDecimolesPerLiter(QuantityValue decimolesperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Molarity FromMicromolesPerLiter(double micromolesperliter) - { - double value = (double) micromolesperliter; - return new Molarity((value/1e-3) * 1e-6d); - } #else public static Molarity FromMicromolesPerLiter(QuantityValue micromolesperliter) +#endif { double value = (double) micromolesperliter; - return new Molarity(((value/1e-3) * 1e-6d)); + return new Molarity(value, MolarityUnit.MicromolesPerLiter); } -#endif /// /// Get Molarity from MillimolesPerLiter. @@ -262,17 +249,13 @@ public static Molarity FromMicromolesPerLiter(QuantityValue micromolesperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Molarity FromMillimolesPerLiter(double millimolesperliter) - { - double value = (double) millimolesperliter; - return new Molarity((value/1e-3) * 1e-3d); - } #else public static Molarity FromMillimolesPerLiter(QuantityValue millimolesperliter) +#endif { double value = (double) millimolesperliter; - return new Molarity(((value/1e-3) * 1e-3d)); + return new Molarity(value, MolarityUnit.MillimolesPerLiter); } -#endif /// /// Get Molarity from MolesPerCubicMeter. @@ -280,17 +263,13 @@ public static Molarity FromMillimolesPerLiter(QuantityValue millimolesperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Molarity FromMolesPerCubicMeter(double molespercubicmeter) - { - double value = (double) molespercubicmeter; - return new Molarity(value); - } #else public static Molarity FromMolesPerCubicMeter(QuantityValue molespercubicmeter) +#endif { double value = (double) molespercubicmeter; - return new Molarity((value)); + return new Molarity(value, MolarityUnit.MolesPerCubicMeter); } -#endif /// /// Get Molarity from MolesPerLiter. @@ -298,17 +277,13 @@ public static Molarity FromMolesPerCubicMeter(QuantityValue molespercubicmeter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Molarity FromMolesPerLiter(double molesperliter) - { - double value = (double) molesperliter; - return new Molarity(value/1e-3); - } #else public static Molarity FromMolesPerLiter(QuantityValue molesperliter) +#endif { double value = (double) molesperliter; - return new Molarity((value/1e-3)); + return new Molarity(value, MolarityUnit.MolesPerLiter); } -#endif /// /// Get Molarity from NanomolesPerLiter. @@ -316,17 +291,13 @@ public static Molarity FromMolesPerLiter(QuantityValue molesperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Molarity FromNanomolesPerLiter(double nanomolesperliter) - { - double value = (double) nanomolesperliter; - return new Molarity((value/1e-3) * 1e-9d); - } #else public static Molarity FromNanomolesPerLiter(QuantityValue nanomolesperliter) +#endif { double value = (double) nanomolesperliter; - return new Molarity(((value/1e-3) * 1e-9d)); + return new Molarity(value, MolarityUnit.NanomolesPerLiter); } -#endif /// /// Get Molarity from PicomolesPerLiter. @@ -334,17 +305,13 @@ public static Molarity FromNanomolesPerLiter(QuantityValue nanomolesperliter) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Molarity FromPicomolesPerLiter(double picomolesperliter) - { - double value = (double) picomolesperliter; - return new Molarity((value/1e-3) * 1e-12d); - } #else public static Molarity FromPicomolesPerLiter(QuantityValue picomolesperliter) +#endif { double value = (double) picomolesperliter; - return new Molarity(((value/1e-3) * 1e-12d)); + return new Molarity(value, MolarityUnit.PicomolesPerLiter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -484,28 +451,7 @@ public static Molarity From(double value, MolarityUnit fromUnit) public static Molarity From(QuantityValue value, MolarityUnit fromUnit) #endif { - switch (fromUnit) - { - case MolarityUnit.CentimolesPerLiter: - return FromCentimolesPerLiter(value); - case MolarityUnit.DecimolesPerLiter: - return FromDecimolesPerLiter(value); - case MolarityUnit.MicromolesPerLiter: - return FromMicromolesPerLiter(value); - case MolarityUnit.MillimolesPerLiter: - return FromMillimolesPerLiter(value); - case MolarityUnit.MolesPerCubicMeter: - return FromMolesPerCubicMeter(value); - case MolarityUnit.MolesPerLiter: - return FromMolesPerLiter(value); - case MolarityUnit.NanomolesPerLiter: - return FromNanomolesPerLiter(value); - case MolarityUnit.PicomolesPerLiter: - return FromPicomolesPerLiter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Molarity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -522,28 +468,8 @@ public static Molarity From(QuantityValue value, MolarityUnit fromUnit) { return null; } - switch (fromUnit) - { - case MolarityUnit.CentimolesPerLiter: - return FromCentimolesPerLiter(value.Value); - case MolarityUnit.DecimolesPerLiter: - return FromDecimolesPerLiter(value.Value); - case MolarityUnit.MicromolesPerLiter: - return FromMicromolesPerLiter(value.Value); - case MolarityUnit.MillimolesPerLiter: - return FromMillimolesPerLiter(value.Value); - case MolarityUnit.MolesPerCubicMeter: - return FromMolesPerCubicMeter(value.Value); - case MolarityUnit.MolesPerLiter: - return FromMolesPerLiter(value.Value); - case MolarityUnit.NanomolesPerLiter: - return FromNanomolesPerLiter(value.Value); - case MolarityUnit.PicomolesPerLiter: - return FromPicomolesPerLiter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Molarity((double)value.Value, fromUnit); } #endif @@ -562,12 +488,29 @@ public static string GetAbbreviation(MolarityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(MolarityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + MolarityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -578,37 +521,37 @@ public static string GetAbbreviation(MolarityUnit unit, [CanBeNull] Culture cult #if !WINDOWS_UWP public static Molarity operator -(Molarity right) { - return new Molarity(-right._molesPerCubicMeter); + return new Molarity(-right.Value, right.Unit); } public static Molarity operator +(Molarity left, Molarity right) { - return new Molarity(left._molesPerCubicMeter + right._molesPerCubicMeter); + return new Molarity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Molarity operator -(Molarity left, Molarity right) { - return new Molarity(left._molesPerCubicMeter - right._molesPerCubicMeter); + return new Molarity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Molarity operator *(double left, Molarity right) { - return new Molarity(left*right._molesPerCubicMeter); + return new Molarity(left * right.Value, right.Unit); } public static Molarity operator *(Molarity left, double right) { - return new Molarity(left._molesPerCubicMeter*(double)right); + return new Molarity(left.Value * right, left.Unit); } public static Molarity operator /(Molarity left, double right) { - return new Molarity(left._molesPerCubicMeter/(double)right); + return new Molarity(left.Value / right, left.Unit); } public static double operator /(Molarity left, Molarity right) { - return Convert.ToDouble(left._molesPerCubicMeter/right._molesPerCubicMeter); + return left.MolesPerCubicMeter / right.MolesPerCubicMeter; } #endif @@ -631,43 +574,43 @@ public int CompareTo(object obj) #endif int CompareTo(Molarity other) { - return _molesPerCubicMeter.CompareTo(other._molesPerCubicMeter); + return AsBaseUnitMolesPerCubicMeter().CompareTo(other.AsBaseUnitMolesPerCubicMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Molarity left, Molarity right) { - return left._molesPerCubicMeter <= right._molesPerCubicMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Molarity left, Molarity right) { - return left._molesPerCubicMeter >= right._molesPerCubicMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Molarity left, Molarity right) { - return left._molesPerCubicMeter < right._molesPerCubicMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Molarity left, Molarity right) { - return left._molesPerCubicMeter > right._molesPerCubicMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Molarity left, Molarity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._molesPerCubicMeter == right._molesPerCubicMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Molarity left, Molarity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._molesPerCubicMeter != right._molesPerCubicMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -679,7 +622,7 @@ public override bool Equals(object obj) return false; } - return _molesPerCubicMeter.Equals(((Molarity) obj)._molesPerCubicMeter); + return AsBaseUnitMolesPerCubicMeter().Equals(((Molarity) obj).AsBaseUnitMolesPerCubicMeter()); } /// @@ -692,12 +635,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Molarity other, Molarity maxError) { - return Math.Abs(_molesPerCubicMeter - other._molesPerCubicMeter) <= maxError._molesPerCubicMeter; + return Math.Abs(AsBaseUnitMolesPerCubicMeter() - other.AsBaseUnitMolesPerCubicMeter()) <= maxError.AsBaseUnitMolesPerCubicMeter(); } public override int GetHashCode() { - return _molesPerCubicMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -707,28 +650,26 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(MolarityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitMolesPerCubicMeter(); + switch (unit) { - case MolarityUnit.CentimolesPerLiter: - return CentimolesPerLiter; - case MolarityUnit.DecimolesPerLiter: - return DecimolesPerLiter; - case MolarityUnit.MicromolesPerLiter: - return MicromolesPerLiter; - case MolarityUnit.MillimolesPerLiter: - return MillimolesPerLiter; - case MolarityUnit.MolesPerCubicMeter: - return MolesPerCubicMeter; - case MolarityUnit.MolesPerLiter: - return MolesPerLiter; - case MolarityUnit.NanomolesPerLiter: - return NanomolesPerLiter; - case MolarityUnit.PicomolesPerLiter: - return PicomolesPerLiter; + case MolarityUnit.CentimolesPerLiter: return (baseUnitValue*1e-3) / 1e-2d; + case MolarityUnit.DecimolesPerLiter: return (baseUnitValue*1e-3) / 1e-1d; + case MolarityUnit.MicromolesPerLiter: return (baseUnitValue*1e-3) / 1e-6d; + case MolarityUnit.MillimolesPerLiter: return (baseUnitValue*1e-3) / 1e-3d; + case MolarityUnit.MolesPerCubicMeter: return baseUnitValue; + case MolarityUnit.MolesPerLiter: return baseUnitValue*1e-3; + case MolarityUnit.NanomolesPerLiter: return (baseUnitValue*1e-3) / 1e-9d; + case MolarityUnit.PicomolesPerLiter: return (baseUnitValue*1e-3) / 1e-12d; default: throw new NotImplementedException("unit: " + unit); @@ -770,7 +711,11 @@ public static Molarity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -789,17 +734,24 @@ public static Molarity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Molarity Parse(string str, [CanBeNull] Culture culture) + public static Molarity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -825,16 +777,41 @@ public static bool TryParse([CanBeNull] string str, out Molarity result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Molarity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Molarity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -847,6 +824,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -860,11 +838,14 @@ public static MolarityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static MolarityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -873,6 +854,8 @@ public static MolarityUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -885,18 +868,18 @@ public static MolarityUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static MolarityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static MolarityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == MolarityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized MolarityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -905,6 +888,7 @@ static MolarityUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is MolesPerCubicMeter /// @@ -916,7 +900,7 @@ static MolarityUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -933,74 +917,136 @@ public string ToString(MolarityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(MolarityUnit unit, [CanBeNull] Culture culture) + public string ToString( + MolarityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(MolarityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + MolarityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(MolarityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + MolarityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Molarity /// - public static Molarity MaxValue - { - get - { - return new Molarity(double.MaxValue); - } - } + public static Molarity MaxValue => new Molarity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Molarity /// - public static Molarity MinValue + public static Molarity MinValue => new Molarity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitMolesPerCubicMeter() { - get + if (Unit == MolarityUnit.MolesPerCubicMeter) { return _value; } + + switch (Unit) { - return new Molarity(double.MinValue); - } - } - } + case MolarityUnit.CentimolesPerLiter: return (_value/1e-3) * 1e-2d; + case MolarityUnit.DecimolesPerLiter: return (_value/1e-3) * 1e-1d; + case MolarityUnit.MicromolesPerLiter: return (_value/1e-3) * 1e-6d; + case MolarityUnit.MillimolesPerLiter: return (_value/1e-3) * 1e-3d; + case MolarityUnit.MolesPerCubicMeter: return _value; + case MolarityUnit.MolesPerLiter: return _value/1e-3; + case MolarityUnit.NanomolesPerLiter: return (_value/1e-3) * 1e-9d; + case MolarityUnit.PicomolesPerLiter: return (_value/1e-3) * 1e-12d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(MolarityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs index 1f42bdf8a2..761c5e5c74 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Permeability : IComparable, IComparable #endif { /// - /// Base unit of Permeability. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PermeabilityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _henriesPerMeter; + public PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Permeability() : this(0) + public Permeability() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Permeability(double henriespermeter) { - _henriesPerMeter = Convert.ToDouble(henriespermeter); + _value = Convert.ToDouble(henriespermeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Permeability(double numericValue, PermeabilityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit HenryPerMeter. + /// + /// Value assuming base unit HenryPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Permeability(long henriespermeter) - { - _henriesPerMeter = Convert.ToDouble(henriespermeter); - } + Permeability(long henriespermeter) : this(Convert.ToDouble(henriespermeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit HenryPerMeter. + /// + /// Value assuming base unit HenryPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Permeability(decimal henriespermeter) - { - _henriesPerMeter = Convert.ToDouble(henriespermeter); - } + Permeability(decimal henriespermeter) : this(Convert.ToDouble(henriespermeter), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public Permeability(double henriespermeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static PermeabilityUnit BaseUnit - { - get { return PermeabilityUnit.HenryPerMeter; } - } + public static PermeabilityUnit BaseUnit => PermeabilityUnit.HenryPerMeter; /// /// All units of measurement for the Permeability quantity. /// public static PermeabilityUnit[] Units { get; } = Enum.GetValues(typeof(PermeabilityUnit)).Cast().ToArray(); - /// /// Get Permeability in HenriesPerMeter. /// - public double HenriesPerMeter - { - get { return _henriesPerMeter; } - } + public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); #endregion #region Static - public static Permeability Zero - { - get { return new Permeability(); } - } + public static Permeability Zero => new Permeability(0, BaseUnit); /// /// Get Permeability from HenriesPerMeter. @@ -152,17 +179,13 @@ public static Permeability Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Permeability FromHenriesPerMeter(double henriespermeter) - { - double value = (double) henriespermeter; - return new Permeability(value); - } #else public static Permeability FromHenriesPerMeter(QuantityValue henriespermeter) +#endif { double value = (double) henriespermeter; - return new Permeability((value)); + return new Permeability(value, PermeabilityUnit.HenryPerMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static Permeability From(double value, PermeabilityUnit fromUnit) public static Permeability From(QuantityValue value, PermeabilityUnit fromUnit) #endif { - switch (fromUnit) - { - case PermeabilityUnit.HenryPerMeter: - return FromHenriesPerMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Permeability((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static Permeability From(QuantityValue value, PermeabilityUnit fromUnit) { return null; } - switch (fromUnit) - { - case PermeabilityUnit.HenryPerMeter: - return FromHenriesPerMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Permeability((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(PermeabilityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + PermeabilityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static Permeability operator -(Permeability right) { - return new Permeability(-right._henriesPerMeter); + return new Permeability(-right.Value, right.Unit); } public static Permeability operator +(Permeability left, Permeability right) { - return new Permeability(left._henriesPerMeter + right._henriesPerMeter); + return new Permeability(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Permeability operator -(Permeability left, Permeability right) { - return new Permeability(left._henriesPerMeter - right._henriesPerMeter); + return new Permeability(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Permeability operator *(double left, Permeability right) { - return new Permeability(left*right._henriesPerMeter); + return new Permeability(left * right.Value, right.Unit); } public static Permeability operator *(Permeability left, double right) { - return new Permeability(left._henriesPerMeter*(double)right); + return new Permeability(left.Value * right, left.Unit); } public static Permeability operator /(Permeability left, double right) { - return new Permeability(left._henriesPerMeter/(double)right); + return new Permeability(left.Value / right, left.Unit); } public static double operator /(Permeability left, Permeability right) { - return Convert.ToDouble(left._henriesPerMeter/right._henriesPerMeter); + return left.HenriesPerMeter / right.HenriesPerMeter; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(Permeability other) { - return _henriesPerMeter.CompareTo(other._henriesPerMeter); + return AsBaseUnitHenriesPerMeter().CompareTo(other.AsBaseUnitHenriesPerMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Permeability left, Permeability right) { - return left._henriesPerMeter <= right._henriesPerMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Permeability left, Permeability right) { - return left._henriesPerMeter >= right._henriesPerMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Permeability left, Permeability right) { - return left._henriesPerMeter < right._henriesPerMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Permeability left, Permeability right) { - return left._henriesPerMeter > right._henriesPerMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Permeability left, Permeability right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._henriesPerMeter == right._henriesPerMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Permeability left, Permeability right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._henriesPerMeter != right._henriesPerMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _henriesPerMeter.Equals(((Permeability) obj)._henriesPerMeter); + return AsBaseUnitHenriesPerMeter().Equals(((Permeability) obj).AsBaseUnitHenriesPerMeter()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Permeability other, Permeability maxError) { - return Math.Abs(_henriesPerMeter - other._henriesPerMeter) <= maxError._henriesPerMeter; + return Math.Abs(AsBaseUnitHenriesPerMeter() - other.AsBaseUnitHenriesPerMeter()) <= maxError.AsBaseUnitHenriesPerMeter(); } public override int GetHashCode() { - return _henriesPerMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(PermeabilityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitHenriesPerMeter(); + switch (unit) { - case PermeabilityUnit.HenryPerMeter: - return HenriesPerMeter; + case PermeabilityUnit.HenryPerMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static Permeability Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static Permeability Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Permeability Parse(string str, [CanBeNull] Culture culture) + public static Permeability Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out Permeability result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Permeability result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Permeability result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static PermeabilityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static PermeabilityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static PermeabilityUnit ParseUnit(string str, [CanBeNull] string cultureN /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static PermeabilityUnit ParseUnit(string str, [CanBeNull] string cultureN #else public #endif - static PermeabilityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static PermeabilityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == PermeabilityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PermeabilityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static PermeabilityUnit ParseUnit(string str, IFormatProvider formatProvider = n #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is HenryPerMeter /// @@ -587,7 +662,7 @@ static PermeabilityUnit ParseUnit(string str, IFormatProvider formatProvider = n /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(PermeabilityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(PermeabilityUnit unit, [CanBeNull] Culture culture) + public string ToString( + PermeabilityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(PermeabilityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + PermeabilityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(PermeabilityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + PermeabilityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Permeability /// - public static Permeability MaxValue - { - get - { - return new Permeability(double.MaxValue); - } - } + public static Permeability MaxValue => new Permeability(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Permeability /// - public static Permeability MinValue + public static Permeability MinValue => new Permeability(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitHenriesPerMeter() { - get + if (Unit == PermeabilityUnit.HenryPerMeter) { return _value; } + + switch (Unit) { - return new Permeability(double.MinValue); - } - } - } + case PermeabilityUnit.HenryPerMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(PermeabilityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs index 2539cd27b6..20a09a57cb 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Permittivity : IComparable, IComparable #endif { /// - /// Base unit of Permittivity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PermittivityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _faradsPerMeter; + public PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Permittivity() : this(0) + public Permittivity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Permittivity(double faradspermeter) { - _faradsPerMeter = Convert.ToDouble(faradspermeter); + _value = Convert.ToDouble(faradspermeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Permittivity(double numericValue, PermittivityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit FaradPerMeter. + /// + /// Value assuming base unit FaradPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Permittivity(long faradspermeter) - { - _faradsPerMeter = Convert.ToDouble(faradspermeter); - } + Permittivity(long faradspermeter) : this(Convert.ToDouble(faradspermeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit FaradPerMeter. + /// + /// Value assuming base unit FaradPerMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Permittivity(decimal faradspermeter) - { - _faradsPerMeter = Convert.ToDouble(faradspermeter); - } + Permittivity(decimal faradspermeter) : this(Convert.ToDouble(faradspermeter), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public Permittivity(double faradspermeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static PermittivityUnit BaseUnit - { - get { return PermittivityUnit.FaradPerMeter; } - } + public static PermittivityUnit BaseUnit => PermittivityUnit.FaradPerMeter; /// /// All units of measurement for the Permittivity quantity. /// public static PermittivityUnit[] Units { get; } = Enum.GetValues(typeof(PermittivityUnit)).Cast().ToArray(); - /// /// Get Permittivity in FaradsPerMeter. /// - public double FaradsPerMeter - { - get { return _faradsPerMeter; } - } + public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); #endregion #region Static - public static Permittivity Zero - { - get { return new Permittivity(); } - } + public static Permittivity Zero => new Permittivity(0, BaseUnit); /// /// Get Permittivity from FaradsPerMeter. @@ -152,17 +179,13 @@ public static Permittivity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Permittivity FromFaradsPerMeter(double faradspermeter) - { - double value = (double) faradspermeter; - return new Permittivity(value); - } #else public static Permittivity FromFaradsPerMeter(QuantityValue faradspermeter) +#endif { double value = (double) faradspermeter; - return new Permittivity((value)); + return new Permittivity(value, PermittivityUnit.FaradPerMeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static Permittivity From(double value, PermittivityUnit fromUnit) public static Permittivity From(QuantityValue value, PermittivityUnit fromUnit) #endif { - switch (fromUnit) - { - case PermittivityUnit.FaradPerMeter: - return FromFaradsPerMeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Permittivity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static Permittivity From(QuantityValue value, PermittivityUnit fromUnit) { return null; } - switch (fromUnit) - { - case PermittivityUnit.FaradPerMeter: - return FromFaradsPerMeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Permittivity((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(PermittivityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(PermittivityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + PermittivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(PermittivityUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static Permittivity operator -(Permittivity right) { - return new Permittivity(-right._faradsPerMeter); + return new Permittivity(-right.Value, right.Unit); } public static Permittivity operator +(Permittivity left, Permittivity right) { - return new Permittivity(left._faradsPerMeter + right._faradsPerMeter); + return new Permittivity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Permittivity operator -(Permittivity left, Permittivity right) { - return new Permittivity(left._faradsPerMeter - right._faradsPerMeter); + return new Permittivity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Permittivity operator *(double left, Permittivity right) { - return new Permittivity(left*right._faradsPerMeter); + return new Permittivity(left * right.Value, right.Unit); } public static Permittivity operator *(Permittivity left, double right) { - return new Permittivity(left._faradsPerMeter*(double)right); + return new Permittivity(left.Value * right, left.Unit); } public static Permittivity operator /(Permittivity left, double right) { - return new Permittivity(left._faradsPerMeter/(double)right); + return new Permittivity(left.Value / right, left.Unit); } public static double operator /(Permittivity left, Permittivity right) { - return Convert.ToDouble(left._faradsPerMeter/right._faradsPerMeter); + return left.FaradsPerMeter / right.FaradsPerMeter; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(Permittivity other) { - return _faradsPerMeter.CompareTo(other._faradsPerMeter); + return AsBaseUnitFaradsPerMeter().CompareTo(other.AsBaseUnitFaradsPerMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Permittivity left, Permittivity right) { - return left._faradsPerMeter <= right._faradsPerMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Permittivity left, Permittivity right) { - return left._faradsPerMeter >= right._faradsPerMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Permittivity left, Permittivity right) { - return left._faradsPerMeter < right._faradsPerMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Permittivity left, Permittivity right) { - return left._faradsPerMeter > right._faradsPerMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Permittivity left, Permittivity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._faradsPerMeter == right._faradsPerMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Permittivity left, Permittivity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._faradsPerMeter != right._faradsPerMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _faradsPerMeter.Equals(((Permittivity) obj)._faradsPerMeter); + return AsBaseUnitFaradsPerMeter().Equals(((Permittivity) obj).AsBaseUnitFaradsPerMeter()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Permittivity other, Permittivity maxError) { - return Math.Abs(_faradsPerMeter - other._faradsPerMeter) <= maxError._faradsPerMeter; + return Math.Abs(AsBaseUnitFaradsPerMeter() - other.AsBaseUnitFaradsPerMeter()) <= maxError.AsBaseUnitFaradsPerMeter(); } public override int GetHashCode() { - return _faradsPerMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(PermittivityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitFaradsPerMeter(); + switch (unit) { - case PermittivityUnit.FaradPerMeter: - return FaradsPerMeter; + case PermittivityUnit.FaradPerMeter: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static Permittivity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static Permittivity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Permittivity Parse(string str, [CanBeNull] Culture culture) + public static Permittivity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out Permittivity result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Permittivity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Permittivity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static PermittivityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static PermittivityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static PermittivityUnit ParseUnit(string str, [CanBeNull] string cultureN /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static PermittivityUnit ParseUnit(string str, [CanBeNull] string cultureN #else public #endif - static PermittivityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static PermittivityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == PermittivityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PermittivityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static PermittivityUnit ParseUnit(string str, IFormatProvider formatProvider = n #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is FaradPerMeter /// @@ -587,7 +662,7 @@ static PermittivityUnit ParseUnit(string str, IFormatProvider formatProvider = n /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(PermittivityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(PermittivityUnit unit, [CanBeNull] Culture culture) + public string ToString( + PermittivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(PermittivityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + PermittivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(PermittivityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + PermittivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Permittivity /// - public static Permittivity MaxValue - { - get - { - return new Permittivity(double.MaxValue); - } - } + public static Permittivity MaxValue => new Permittivity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Permittivity /// - public static Permittivity MinValue + public static Permittivity MinValue => new Permittivity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitFaradsPerMeter() { - get + if (Unit == PermittivityUnit.FaradPerMeter) { return _value; } + + switch (Unit) { - return new Permittivity(double.MinValue); - } - } - } + case PermittivityUnit.FaradPerMeter: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(PermittivityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Power.g.cs b/UnitsNet/GeneratedCode/Quantities/Power.g.cs index cf78ac72df..d049dbe15c 100644 --- a/UnitsNet/GeneratedCode/Quantities/Power.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Power.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Power : IComparable, IComparable #endif { /// - /// Base unit of Power. + /// The numeric value this quantity was constructed with. /// - private readonly decimal _watts; + private readonly decimal _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public decimal Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Power() : this(0) + public Power() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Power(double watts) { - _watts = Convert.ToDecimal(watts); + _value = Convert.ToDecimal(watts); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Power(decimal numericValue, PowerUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Watt. + /// + /// Value assuming base unit Watt. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Power(long watts) - { - _watts = Convert.ToDecimal(watts); - } + Power(long watts) : this(Convert.ToDecimal(watts), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Watt. + /// + /// Value assuming base unit Watt. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Power(decimal watts) - { - _watts = Convert.ToDecimal(watts); - } + Power(decimal watts) : this(Convert.ToDecimal(watts), BaseUnit) { } #region Properties @@ -119,184 +156,98 @@ public Power(double watts) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static PowerUnit BaseUnit - { - get { return PowerUnit.Watt; } - } + public static PowerUnit BaseUnit => PowerUnit.Watt; /// /// All units of measurement for the Power quantity. /// public static PowerUnit[] Units { get; } = Enum.GetValues(typeof(PowerUnit)).Cast().ToArray(); - /// /// Get Power in BoilerHorsepower. /// - public double BoilerHorsepower - { - get { return Convert.ToDouble(_watts/9812.5m); } - } - + public double BoilerHorsepower => As(PowerUnit.BoilerHorsepower); /// /// Get Power in BritishThermalUnitsPerHour. /// - public double BritishThermalUnitsPerHour - { - get { return Convert.ToDouble(_watts/0.293071m); } - } - + public double BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); /// /// Get Power in Decawatts. /// - public double Decawatts - { - get { return Convert.ToDouble((_watts) / 1e1m); } - } - + public double Decawatts => As(PowerUnit.Decawatt); /// /// Get Power in Deciwatts. /// - public double Deciwatts - { - get { return Convert.ToDouble((_watts) / 1e-1m); } - } - + public double Deciwatts => As(PowerUnit.Deciwatt); /// /// Get Power in ElectricalHorsepower. /// - public double ElectricalHorsepower - { - get { return Convert.ToDouble(_watts/746m); } - } - + public double ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); /// /// Get Power in Femtowatts. /// - public double Femtowatts - { - get { return Convert.ToDouble((_watts) / 1e-15m); } - } - + public double Femtowatts => As(PowerUnit.Femtowatt); /// /// Get Power in Gigawatts. /// - public double Gigawatts - { - get { return Convert.ToDouble((_watts) / 1e9m); } - } - + public double Gigawatts => As(PowerUnit.Gigawatt); /// /// Get Power in HydraulicHorsepower. /// - public double HydraulicHorsepower - { - get { return Convert.ToDouble(_watts/745.69988145m); } - } - + public double HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); /// /// Get Power in KilobritishThermalUnitsPerHour. /// - public double KilobritishThermalUnitsPerHour - { - get { return Convert.ToDouble((_watts/0.293071m) / 1e3m); } - } - + public double KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); /// /// Get Power in Kilowatts. /// - public double Kilowatts - { - get { return Convert.ToDouble((_watts) / 1e3m); } - } - + public double Kilowatts => As(PowerUnit.Kilowatt); /// /// Get Power in MechanicalHorsepower. /// - public double MechanicalHorsepower - { - get { return Convert.ToDouble(_watts/745.69m); } - } - + public double MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); /// /// Get Power in Megawatts. /// - public double Megawatts - { - get { return Convert.ToDouble((_watts) / 1e6m); } - } - + public double Megawatts => As(PowerUnit.Megawatt); /// /// Get Power in MetricHorsepower. /// - public double MetricHorsepower - { - get { return Convert.ToDouble(_watts/735.49875m); } - } - + public double MetricHorsepower => As(PowerUnit.MetricHorsepower); /// /// Get Power in Microwatts. /// - public double Microwatts - { - get { return Convert.ToDouble((_watts) / 1e-6m); } - } - + public double Microwatts => As(PowerUnit.Microwatt); /// /// Get Power in Milliwatts. /// - public double Milliwatts - { - get { return Convert.ToDouble((_watts) / 1e-3m); } - } - + public double Milliwatts => As(PowerUnit.Milliwatt); /// /// Get Power in Nanowatts. /// - public double Nanowatts - { - get { return Convert.ToDouble((_watts) / 1e-9m); } - } - + public double Nanowatts => As(PowerUnit.Nanowatt); /// /// Get Power in Petawatts. /// - public double Petawatts - { - get { return Convert.ToDouble((_watts) / 1e15m); } - } - + public double Petawatts => As(PowerUnit.Petawatt); /// /// Get Power in Picowatts. /// - public double Picowatts - { - get { return Convert.ToDouble((_watts) / 1e-12m); } - } - + public double Picowatts => As(PowerUnit.Picowatt); /// /// Get Power in Terawatts. /// - public double Terawatts - { - get { return Convert.ToDouble((_watts) / 1e12m); } - } - + public double Terawatts => As(PowerUnit.Terawatt); /// /// Get Power in Watts. /// - public double Watts - { - get { return Convert.ToDouble(_watts); } - } + public double Watts => As(PowerUnit.Watt); #endregion #region Static - public static Power Zero - { - get { return new Power(); } - } + public static Power Zero => new Power(0, BaseUnit); /// /// Get Power from BoilerHorsepower. @@ -304,17 +255,13 @@ public static Power Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromBoilerHorsepower(double boilerhorsepower) - { - double value = (double) boilerhorsepower; - return new Power(Convert.ToDecimal(value*9812.5d)); - } #else public static Power FromBoilerHorsepower(QuantityValue boilerhorsepower) +#endif { - double value = (double) boilerhorsepower; - return new Power((Convert.ToDecimal(value*9812.5d))); + decimal value = (decimal) boilerhorsepower; + return new Power(value, PowerUnit.BoilerHorsepower); } -#endif /// /// Get Power from BritishThermalUnitsPerHour. @@ -322,17 +269,13 @@ public static Power FromBoilerHorsepower(QuantityValue boilerhorsepower) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromBritishThermalUnitsPerHour(double britishthermalunitsperhour) - { - double value = (double) britishthermalunitsperhour; - return new Power(Convert.ToDecimal(value*0.293071d)); - } #else public static Power FromBritishThermalUnitsPerHour(QuantityValue britishthermalunitsperhour) +#endif { - double value = (double) britishthermalunitsperhour; - return new Power((Convert.ToDecimal(value*0.293071d))); + decimal value = (decimal) britishthermalunitsperhour; + return new Power(value, PowerUnit.BritishThermalUnitPerHour); } -#endif /// /// Get Power from Decawatts. @@ -340,17 +283,13 @@ public static Power FromBritishThermalUnitsPerHour(QuantityValue britishthermalu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromDecawatts(double decawatts) - { - double value = (double) decawatts; - return new Power(Convert.ToDecimal((value) * 1e1d)); - } #else public static Power FromDecawatts(QuantityValue decawatts) +#endif { - double value = (double) decawatts; - return new Power((Convert.ToDecimal((value) * 1e1d))); + decimal value = (decimal) decawatts; + return new Power(value, PowerUnit.Decawatt); } -#endif /// /// Get Power from Deciwatts. @@ -358,17 +297,13 @@ public static Power FromDecawatts(QuantityValue decawatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromDeciwatts(double deciwatts) - { - double value = (double) deciwatts; - return new Power(Convert.ToDecimal((value) * 1e-1d)); - } #else public static Power FromDeciwatts(QuantityValue deciwatts) +#endif { - double value = (double) deciwatts; - return new Power((Convert.ToDecimal((value) * 1e-1d))); + decimal value = (decimal) deciwatts; + return new Power(value, PowerUnit.Deciwatt); } -#endif /// /// Get Power from ElectricalHorsepower. @@ -376,17 +311,13 @@ public static Power FromDeciwatts(QuantityValue deciwatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromElectricalHorsepower(double electricalhorsepower) - { - double value = (double) electricalhorsepower; - return new Power(Convert.ToDecimal(value*746d)); - } #else public static Power FromElectricalHorsepower(QuantityValue electricalhorsepower) +#endif { - double value = (double) electricalhorsepower; - return new Power((Convert.ToDecimal(value*746d))); + decimal value = (decimal) electricalhorsepower; + return new Power(value, PowerUnit.ElectricalHorsepower); } -#endif /// /// Get Power from Femtowatts. @@ -394,17 +325,13 @@ public static Power FromElectricalHorsepower(QuantityValue electricalhorsepower) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromFemtowatts(double femtowatts) - { - double value = (double) femtowatts; - return new Power(Convert.ToDecimal((value) * 1e-15d)); - } #else public static Power FromFemtowatts(QuantityValue femtowatts) +#endif { - double value = (double) femtowatts; - return new Power((Convert.ToDecimal((value) * 1e-15d))); + decimal value = (decimal) femtowatts; + return new Power(value, PowerUnit.Femtowatt); } -#endif /// /// Get Power from Gigawatts. @@ -412,17 +339,13 @@ public static Power FromFemtowatts(QuantityValue femtowatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromGigawatts(double gigawatts) - { - double value = (double) gigawatts; - return new Power(Convert.ToDecimal((value) * 1e9d)); - } #else public static Power FromGigawatts(QuantityValue gigawatts) +#endif { - double value = (double) gigawatts; - return new Power((Convert.ToDecimal((value) * 1e9d))); + decimal value = (decimal) gigawatts; + return new Power(value, PowerUnit.Gigawatt); } -#endif /// /// Get Power from HydraulicHorsepower. @@ -430,17 +353,13 @@ public static Power FromGigawatts(QuantityValue gigawatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromHydraulicHorsepower(double hydraulichorsepower) - { - double value = (double) hydraulichorsepower; - return new Power(Convert.ToDecimal(value*745.69988145d)); - } #else public static Power FromHydraulicHorsepower(QuantityValue hydraulichorsepower) +#endif { - double value = (double) hydraulichorsepower; - return new Power((Convert.ToDecimal(value*745.69988145d))); + decimal value = (decimal) hydraulichorsepower; + return new Power(value, PowerUnit.HydraulicHorsepower); } -#endif /// /// Get Power from KilobritishThermalUnitsPerHour. @@ -448,17 +367,13 @@ public static Power FromHydraulicHorsepower(QuantityValue hydraulichorsepower) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromKilobritishThermalUnitsPerHour(double kilobritishthermalunitsperhour) - { - double value = (double) kilobritishthermalunitsperhour; - return new Power(Convert.ToDecimal((value*0.293071d) * 1e3d)); - } #else public static Power FromKilobritishThermalUnitsPerHour(QuantityValue kilobritishthermalunitsperhour) +#endif { - double value = (double) kilobritishthermalunitsperhour; - return new Power((Convert.ToDecimal((value*0.293071d) * 1e3d))); + decimal value = (decimal) kilobritishthermalunitsperhour; + return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); } -#endif /// /// Get Power from Kilowatts. @@ -466,17 +381,13 @@ public static Power FromKilobritishThermalUnitsPerHour(QuantityValue kilobritish #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromKilowatts(double kilowatts) - { - double value = (double) kilowatts; - return new Power(Convert.ToDecimal((value) * 1e3d)); - } #else public static Power FromKilowatts(QuantityValue kilowatts) +#endif { - double value = (double) kilowatts; - return new Power((Convert.ToDecimal((value) * 1e3d))); + decimal value = (decimal) kilowatts; + return new Power(value, PowerUnit.Kilowatt); } -#endif /// /// Get Power from MechanicalHorsepower. @@ -484,17 +395,13 @@ public static Power FromKilowatts(QuantityValue kilowatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromMechanicalHorsepower(double mechanicalhorsepower) - { - double value = (double) mechanicalhorsepower; - return new Power(Convert.ToDecimal(value*745.69d)); - } #else public static Power FromMechanicalHorsepower(QuantityValue mechanicalhorsepower) +#endif { - double value = (double) mechanicalhorsepower; - return new Power((Convert.ToDecimal(value*745.69d))); + decimal value = (decimal) mechanicalhorsepower; + return new Power(value, PowerUnit.MechanicalHorsepower); } -#endif /// /// Get Power from Megawatts. @@ -502,17 +409,13 @@ public static Power FromMechanicalHorsepower(QuantityValue mechanicalhorsepower) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromMegawatts(double megawatts) - { - double value = (double) megawatts; - return new Power(Convert.ToDecimal((value) * 1e6d)); - } #else public static Power FromMegawatts(QuantityValue megawatts) +#endif { - double value = (double) megawatts; - return new Power((Convert.ToDecimal((value) * 1e6d))); + decimal value = (decimal) megawatts; + return new Power(value, PowerUnit.Megawatt); } -#endif /// /// Get Power from MetricHorsepower. @@ -520,17 +423,13 @@ public static Power FromMegawatts(QuantityValue megawatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromMetricHorsepower(double metrichorsepower) - { - double value = (double) metrichorsepower; - return new Power(Convert.ToDecimal(value*735.49875d)); - } #else public static Power FromMetricHorsepower(QuantityValue metrichorsepower) +#endif { - double value = (double) metrichorsepower; - return new Power((Convert.ToDecimal(value*735.49875d))); + decimal value = (decimal) metrichorsepower; + return new Power(value, PowerUnit.MetricHorsepower); } -#endif /// /// Get Power from Microwatts. @@ -538,17 +437,13 @@ public static Power FromMetricHorsepower(QuantityValue metrichorsepower) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromMicrowatts(double microwatts) - { - double value = (double) microwatts; - return new Power(Convert.ToDecimal((value) * 1e-6d)); - } #else public static Power FromMicrowatts(QuantityValue microwatts) +#endif { - double value = (double) microwatts; - return new Power((Convert.ToDecimal((value) * 1e-6d))); + decimal value = (decimal) microwatts; + return new Power(value, PowerUnit.Microwatt); } -#endif /// /// Get Power from Milliwatts. @@ -556,17 +451,13 @@ public static Power FromMicrowatts(QuantityValue microwatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromMilliwatts(double milliwatts) - { - double value = (double) milliwatts; - return new Power(Convert.ToDecimal((value) * 1e-3d)); - } #else public static Power FromMilliwatts(QuantityValue milliwatts) +#endif { - double value = (double) milliwatts; - return new Power((Convert.ToDecimal((value) * 1e-3d))); + decimal value = (decimal) milliwatts; + return new Power(value, PowerUnit.Milliwatt); } -#endif /// /// Get Power from Nanowatts. @@ -574,17 +465,13 @@ public static Power FromMilliwatts(QuantityValue milliwatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromNanowatts(double nanowatts) - { - double value = (double) nanowatts; - return new Power(Convert.ToDecimal((value) * 1e-9d)); - } #else public static Power FromNanowatts(QuantityValue nanowatts) +#endif { - double value = (double) nanowatts; - return new Power((Convert.ToDecimal((value) * 1e-9d))); + decimal value = (decimal) nanowatts; + return new Power(value, PowerUnit.Nanowatt); } -#endif /// /// Get Power from Petawatts. @@ -592,17 +479,13 @@ public static Power FromNanowatts(QuantityValue nanowatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromPetawatts(double petawatts) - { - double value = (double) petawatts; - return new Power(Convert.ToDecimal((value) * 1e15d)); - } #else public static Power FromPetawatts(QuantityValue petawatts) +#endif { - double value = (double) petawatts; - return new Power((Convert.ToDecimal((value) * 1e15d))); + decimal value = (decimal) petawatts; + return new Power(value, PowerUnit.Petawatt); } -#endif /// /// Get Power from Picowatts. @@ -610,17 +493,13 @@ public static Power FromPetawatts(QuantityValue petawatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromPicowatts(double picowatts) - { - double value = (double) picowatts; - return new Power(Convert.ToDecimal((value) * 1e-12d)); - } #else public static Power FromPicowatts(QuantityValue picowatts) +#endif { - double value = (double) picowatts; - return new Power((Convert.ToDecimal((value) * 1e-12d))); + decimal value = (decimal) picowatts; + return new Power(value, PowerUnit.Picowatt); } -#endif /// /// Get Power from Terawatts. @@ -628,17 +507,13 @@ public static Power FromPicowatts(QuantityValue picowatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromTerawatts(double terawatts) - { - double value = (double) terawatts; - return new Power(Convert.ToDecimal((value) * 1e12d)); - } #else public static Power FromTerawatts(QuantityValue terawatts) +#endif { - double value = (double) terawatts; - return new Power((Convert.ToDecimal((value) * 1e12d))); + decimal value = (decimal) terawatts; + return new Power(value, PowerUnit.Terawatt); } -#endif /// /// Get Power from Watts. @@ -646,17 +521,13 @@ public static Power FromTerawatts(QuantityValue terawatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Power FromWatts(double watts) - { - double value = (double) watts; - return new Power(Convert.ToDecimal(value)); - } #else public static Power FromWatts(QuantityValue watts) +#endif { - double value = (double) watts; - return new Power((Convert.ToDecimal(value))); + decimal value = (decimal) watts; + return new Power(value, PowerUnit.Watt); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -976,52 +847,7 @@ public static Power From(double value, PowerUnit fromUnit) public static Power From(QuantityValue value, PowerUnit fromUnit) #endif { - switch (fromUnit) - { - case PowerUnit.BoilerHorsepower: - return FromBoilerHorsepower(value); - case PowerUnit.BritishThermalUnitPerHour: - return FromBritishThermalUnitsPerHour(value); - case PowerUnit.Decawatt: - return FromDecawatts(value); - case PowerUnit.Deciwatt: - return FromDeciwatts(value); - case PowerUnit.ElectricalHorsepower: - return FromElectricalHorsepower(value); - case PowerUnit.Femtowatt: - return FromFemtowatts(value); - case PowerUnit.Gigawatt: - return FromGigawatts(value); - case PowerUnit.HydraulicHorsepower: - return FromHydraulicHorsepower(value); - case PowerUnit.KilobritishThermalUnitPerHour: - return FromKilobritishThermalUnitsPerHour(value); - case PowerUnit.Kilowatt: - return FromKilowatts(value); - case PowerUnit.MechanicalHorsepower: - return FromMechanicalHorsepower(value); - case PowerUnit.Megawatt: - return FromMegawatts(value); - case PowerUnit.MetricHorsepower: - return FromMetricHorsepower(value); - case PowerUnit.Microwatt: - return FromMicrowatts(value); - case PowerUnit.Milliwatt: - return FromMilliwatts(value); - case PowerUnit.Nanowatt: - return FromNanowatts(value); - case PowerUnit.Petawatt: - return FromPetawatts(value); - case PowerUnit.Picowatt: - return FromPicowatts(value); - case PowerUnit.Terawatt: - return FromTerawatts(value); - case PowerUnit.Watt: - return FromWatts(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Power((decimal)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1038,52 +864,8 @@ public static Power From(QuantityValue value, PowerUnit fromUnit) { return null; } - switch (fromUnit) - { - case PowerUnit.BoilerHorsepower: - return FromBoilerHorsepower(value.Value); - case PowerUnit.BritishThermalUnitPerHour: - return FromBritishThermalUnitsPerHour(value.Value); - case PowerUnit.Decawatt: - return FromDecawatts(value.Value); - case PowerUnit.Deciwatt: - return FromDeciwatts(value.Value); - case PowerUnit.ElectricalHorsepower: - return FromElectricalHorsepower(value.Value); - case PowerUnit.Femtowatt: - return FromFemtowatts(value.Value); - case PowerUnit.Gigawatt: - return FromGigawatts(value.Value); - case PowerUnit.HydraulicHorsepower: - return FromHydraulicHorsepower(value.Value); - case PowerUnit.KilobritishThermalUnitPerHour: - return FromKilobritishThermalUnitsPerHour(value.Value); - case PowerUnit.Kilowatt: - return FromKilowatts(value.Value); - case PowerUnit.MechanicalHorsepower: - return FromMechanicalHorsepower(value.Value); - case PowerUnit.Megawatt: - return FromMegawatts(value.Value); - case PowerUnit.MetricHorsepower: - return FromMetricHorsepower(value.Value); - case PowerUnit.Microwatt: - return FromMicrowatts(value.Value); - case PowerUnit.Milliwatt: - return FromMilliwatts(value.Value); - case PowerUnit.Nanowatt: - return FromNanowatts(value.Value); - case PowerUnit.Petawatt: - return FromPetawatts(value.Value); - case PowerUnit.Picowatt: - return FromPicowatts(value.Value); - case PowerUnit.Terawatt: - return FromTerawatts(value.Value); - case PowerUnit.Watt: - return FromWatts(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Power((decimal)value.Value, fromUnit); } #endif @@ -1102,12 +884,29 @@ public static string GetAbbreviation(PowerUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(PowerUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + PowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1118,37 +917,37 @@ public static string GetAbbreviation(PowerUnit unit, [CanBeNull] Culture culture #if !WINDOWS_UWP public static Power operator -(Power right) { - return new Power(-right._watts); + return new Power(-right.Value, right.Unit); } public static Power operator +(Power left, Power right) { - return new Power(left._watts + right._watts); + return new Power(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Power operator -(Power left, Power right) { - return new Power(left._watts - right._watts); + return new Power(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Power operator *(decimal left, Power right) { - return new Power(left*right._watts); + return new Power(left * right.Value, right.Unit); } - public static Power operator *(Power left, double right) + public static Power operator *(Power left, decimal right) { - return new Power(left._watts*(decimal)right); + return new Power(left.Value * right, left.Unit); } - public static Power operator /(Power left, double right) + public static Power operator /(Power left, decimal right) { - return new Power(left._watts/(decimal)right); + return new Power(left.Value / right, left.Unit); } public static double operator /(Power left, Power right) { - return Convert.ToDouble(left._watts/right._watts); + return left.Watts / right.Watts; } #endif @@ -1171,41 +970,41 @@ public int CompareTo(object obj) #endif int CompareTo(Power other) { - return _watts.CompareTo(other._watts); + return AsBaseUnitWatts().CompareTo(other.AsBaseUnitWatts()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Power left, Power right) { - return left._watts <= right._watts; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Power left, Power right) { - return left._watts >= right._watts; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Power left, Power right) { - return left._watts < right._watts; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Power left, Power right) { - return left._watts > right._watts; + return left.Value > right.AsBaseNumericType(left.Unit); } public static bool operator ==(Power left, Power right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._watts == right._watts; + return left.Value == right.AsBaseNumericType(left.Unit); } public static bool operator !=(Power left, Power right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._watts != right._watts; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1216,7 +1015,7 @@ public override bool Equals(object obj) return false; } - return _watts.Equals(((Power) obj)._watts); + return AsBaseUnitWatts().Equals(((Power) obj).AsBaseUnitWatts()); } /// @@ -1229,12 +1028,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Power other, Power maxError) { - return Math.Abs(_watts - other._watts) <= maxError._watts; + return Math.Abs(AsBaseUnitWatts() - other.AsBaseUnitWatts()) <= maxError.AsBaseUnitWatts(); } public override int GetHashCode() { - return _watts.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1244,52 +1043,38 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(PowerUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + decimal baseUnitValue = AsBaseUnitWatts(); + switch (unit) { - case PowerUnit.BoilerHorsepower: - return BoilerHorsepower; - case PowerUnit.BritishThermalUnitPerHour: - return BritishThermalUnitsPerHour; - case PowerUnit.Decawatt: - return Decawatts; - case PowerUnit.Deciwatt: - return Deciwatts; - case PowerUnit.ElectricalHorsepower: - return ElectricalHorsepower; - case PowerUnit.Femtowatt: - return Femtowatts; - case PowerUnit.Gigawatt: - return Gigawatts; - case PowerUnit.HydraulicHorsepower: - return HydraulicHorsepower; - case PowerUnit.KilobritishThermalUnitPerHour: - return KilobritishThermalUnitsPerHour; - case PowerUnit.Kilowatt: - return Kilowatts; - case PowerUnit.MechanicalHorsepower: - return MechanicalHorsepower; - case PowerUnit.Megawatt: - return Megawatts; - case PowerUnit.MetricHorsepower: - return MetricHorsepower; - case PowerUnit.Microwatt: - return Microwatts; - case PowerUnit.Milliwatt: - return Milliwatts; - case PowerUnit.Nanowatt: - return Nanowatts; - case PowerUnit.Petawatt: - return Petawatts; - case PowerUnit.Picowatt: - return Picowatts; - case PowerUnit.Terawatt: - return Terawatts; - case PowerUnit.Watt: - return Watts; + case PowerUnit.BoilerHorsepower: return Convert.ToDouble(baseUnitValue/9812.5m); + case PowerUnit.BritishThermalUnitPerHour: return Convert.ToDouble(baseUnitValue/0.293071m); + case PowerUnit.Decawatt: return Convert.ToDouble((baseUnitValue) / 1e1m); + case PowerUnit.Deciwatt: return Convert.ToDouble((baseUnitValue) / 1e-1m); + case PowerUnit.ElectricalHorsepower: return Convert.ToDouble(baseUnitValue/746m); + case PowerUnit.Femtowatt: return Convert.ToDouble((baseUnitValue) / 1e-15m); + case PowerUnit.Gigawatt: return Convert.ToDouble((baseUnitValue) / 1e9m); + case PowerUnit.HydraulicHorsepower: return Convert.ToDouble(baseUnitValue/745.69988145m); + case PowerUnit.KilobritishThermalUnitPerHour: return Convert.ToDouble((baseUnitValue/0.293071m) / 1e3m); + case PowerUnit.Kilowatt: return Convert.ToDouble((baseUnitValue) / 1e3m); + case PowerUnit.MechanicalHorsepower: return Convert.ToDouble(baseUnitValue/745.69m); + case PowerUnit.Megawatt: return Convert.ToDouble((baseUnitValue) / 1e6m); + case PowerUnit.MetricHorsepower: return Convert.ToDouble(baseUnitValue/735.49875m); + case PowerUnit.Microwatt: return Convert.ToDouble((baseUnitValue) / 1e-6m); + case PowerUnit.Milliwatt: return Convert.ToDouble((baseUnitValue) / 1e-3m); + case PowerUnit.Nanowatt: return Convert.ToDouble((baseUnitValue) / 1e-9m); + case PowerUnit.Petawatt: return Convert.ToDouble((baseUnitValue) / 1e15m); + case PowerUnit.Picowatt: return Convert.ToDouble((baseUnitValue) / 1e-12m); + case PowerUnit.Terawatt: return Convert.ToDouble((baseUnitValue) / 1e12m); + case PowerUnit.Watt: return Convert.ToDouble(baseUnitValue); default: throw new NotImplementedException("unit: " + unit); @@ -1331,7 +1116,11 @@ public static Power Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1350,17 +1139,24 @@ public static Power Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Power Parse(string str, [CanBeNull] Culture culture) + public static Power Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1386,16 +1182,41 @@ public static bool TryParse([CanBeNull] string str, out Power result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Power result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Power result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1408,6 +1229,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1421,11 +1243,14 @@ public static PowerUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static PowerUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1434,6 +1259,8 @@ public static PowerUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1446,18 +1273,18 @@ public static PowerUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static PowerUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static PowerUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == PowerUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1466,6 +1293,7 @@ static PowerUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Watt /// @@ -1477,7 +1305,7 @@ static PowerUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1494,74 +1322,148 @@ public string ToString(PowerUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(PowerUnit unit, [CanBeNull] Culture culture) + public string ToString( + PowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(PowerUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + PowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(PowerUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + PowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Power /// - public static Power MaxValue - { - get - { - return new Power(decimal.MaxValue); - } - } + public static Power MaxValue => new Power(decimal.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Power /// - public static Power MinValue + public static Power MinValue => new Power(decimal.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private decimal AsBaseUnitWatts() { - get + if (Unit == PowerUnit.Watt) { return _value; } + + switch (Unit) { - return new Power(decimal.MinValue); - } - } - } + case PowerUnit.BoilerHorsepower: return Convert.ToDecimal(_value*9812.5m); + case PowerUnit.BritishThermalUnitPerHour: return Convert.ToDecimal(_value*0.293071m); + case PowerUnit.Decawatt: return Convert.ToDecimal((_value) * 1e1m); + case PowerUnit.Deciwatt: return Convert.ToDecimal((_value) * 1e-1m); + case PowerUnit.ElectricalHorsepower: return Convert.ToDecimal(_value*746m); + case PowerUnit.Femtowatt: return Convert.ToDecimal((_value) * 1e-15m); + case PowerUnit.Gigawatt: return Convert.ToDecimal((_value) * 1e9m); + case PowerUnit.HydraulicHorsepower: return Convert.ToDecimal(_value*745.69988145m); + case PowerUnit.KilobritishThermalUnitPerHour: return Convert.ToDecimal((_value*0.293071m) * 1e3m); + case PowerUnit.Kilowatt: return Convert.ToDecimal((_value) * 1e3m); + case PowerUnit.MechanicalHorsepower: return Convert.ToDecimal(_value*745.69m); + case PowerUnit.Megawatt: return Convert.ToDecimal((_value) * 1e6m); + case PowerUnit.MetricHorsepower: return Convert.ToDecimal(_value*735.49875m); + case PowerUnit.Microwatt: return Convert.ToDecimal((_value) * 1e-6m); + case PowerUnit.Milliwatt: return Convert.ToDecimal((_value) * 1e-3m); + case PowerUnit.Nanowatt: return Convert.ToDecimal((_value) * 1e-9m); + case PowerUnit.Petawatt: return Convert.ToDecimal((_value) * 1e15m); + case PowerUnit.Picowatt: return Convert.ToDecimal((_value) * 1e-12m); + case PowerUnit.Terawatt: return Convert.ToDecimal((_value) * 1e12m); + case PowerUnit.Watt: return Convert.ToDecimal(_value); + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private decimal AsBaseNumericType(PowerUnit unit) => Convert.ToDecimal(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs index f47773f48c..d2125d8796 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct PowerRatio : IComparable, IComparable #endif { /// - /// Base unit of PowerRatio. + /// The numeric value this quantity was constructed with. /// - private readonly double _decibelWatts; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PowerRatioUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public PowerRatio() : this(0) + public PowerRatio() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public PowerRatio(double decibelwatts) { - _decibelWatts = Convert.ToDouble(decibelwatts); + _value = Convert.ToDouble(decibelwatts); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + PowerRatio(double numericValue, PowerRatioUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit DecibelWatt. + /// + /// Value assuming base unit DecibelWatt. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - PowerRatio(long decibelwatts) - { - _decibelWatts = Convert.ToDouble(decibelwatts); - } + PowerRatio(long decibelwatts) : this(Convert.ToDouble(decibelwatts), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit DecibelWatt. + /// + /// Value assuming base unit DecibelWatt. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - PowerRatio(decimal decibelwatts) - { - _decibelWatts = Convert.ToDouble(decibelwatts); - } + PowerRatio(decimal decibelwatts) : this(Convert.ToDouble(decibelwatts), BaseUnit) { } #region Properties @@ -119,40 +156,26 @@ public PowerRatio(double decibelwatts) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static PowerRatioUnit BaseUnit - { - get { return PowerRatioUnit.DecibelWatt; } - } + public static PowerRatioUnit BaseUnit => PowerRatioUnit.DecibelWatt; /// /// All units of measurement for the PowerRatio quantity. /// public static PowerRatioUnit[] Units { get; } = Enum.GetValues(typeof(PowerRatioUnit)).Cast().ToArray(); - /// /// Get PowerRatio in DecibelMilliwatts. /// - public double DecibelMilliwatts - { - get { return _decibelWatts + 30; } - } - + public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); /// /// Get PowerRatio in DecibelWatts. /// - public double DecibelWatts - { - get { return _decibelWatts; } - } + public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); #endregion #region Static - public static PowerRatio Zero - { - get { return new PowerRatio(); } - } + public static PowerRatio Zero => new PowerRatio(0, BaseUnit); /// /// Get PowerRatio from DecibelMilliwatts. @@ -160,17 +183,13 @@ public static PowerRatio Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static PowerRatio FromDecibelMilliwatts(double decibelmilliwatts) - { - double value = (double) decibelmilliwatts; - return new PowerRatio(value - 30); - } #else public static PowerRatio FromDecibelMilliwatts(QuantityValue decibelmilliwatts) +#endif { double value = (double) decibelmilliwatts; - return new PowerRatio((value - 30)); + return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); } -#endif /// /// Get PowerRatio from DecibelWatts. @@ -178,17 +197,13 @@ public static PowerRatio FromDecibelMilliwatts(QuantityValue decibelmilliwatts) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static PowerRatio FromDecibelWatts(double decibelwatts) - { - double value = (double) decibelwatts; - return new PowerRatio(value); - } #else public static PowerRatio FromDecibelWatts(QuantityValue decibelwatts) +#endif { double value = (double) decibelwatts; - return new PowerRatio((value)); + return new PowerRatio(value, PowerRatioUnit.DecibelWatt); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -238,16 +253,7 @@ public static PowerRatio From(double value, PowerRatioUnit fromUnit) public static PowerRatio From(QuantityValue value, PowerRatioUnit fromUnit) #endif { - switch (fromUnit) - { - case PowerRatioUnit.DecibelMilliwatt: - return FromDecibelMilliwatts(value); - case PowerRatioUnit.DecibelWatt: - return FromDecibelWatts(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new PowerRatio((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -264,16 +270,8 @@ public static PowerRatio From(QuantityValue value, PowerRatioUnit fromUnit) { return null; } - switch (fromUnit) - { - case PowerRatioUnit.DecibelMilliwatt: - return FromDecibelMilliwatts(value.Value); - case PowerRatioUnit.DecibelWatt: - return FromDecibelWatts(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new PowerRatio((double)value.Value, fromUnit); } #endif @@ -292,12 +290,29 @@ public static string GetAbbreviation(PowerRatioUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(PowerRatioUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + PowerRatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -308,45 +323,45 @@ public static string GetAbbreviation(PowerRatioUnit unit, [CanBeNull] Culture cu #if !WINDOWS_UWP public static PowerRatio operator -(PowerRatio right) { - return new PowerRatio(-right._decibelWatts); + return new PowerRatio(-right.Value, right.Unit); } 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._decibelWatts/10) + Math.Pow(10, right._decibelWatts/10))); + return new PowerRatio(10*Math.Log10(Math.Pow(10, left.Value/10) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/10)), left.Unit); } 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._decibelWatts/10) - Math.Pow(10, right._decibelWatts/10))); + return new PowerRatio(10*Math.Log10(Math.Pow(10, left.Value/10) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/10)), left.Unit); } public static PowerRatio operator *(double left, PowerRatio right) { // Logarithmic multiplication = addition - return new PowerRatio(left + right._decibelWatts); + return new PowerRatio(left + right.Value, right.Unit); } public static PowerRatio operator *(PowerRatio left, double right) { // Logarithmic multiplication = addition - return new PowerRatio(left._decibelWatts + (double)right); + return new PowerRatio(left.Value + (double)right, left.Unit); } public static PowerRatio operator /(PowerRatio left, double right) { // Logarithmic division = subtraction - return new PowerRatio(left._decibelWatts - (double)right); + return new PowerRatio(left.Value - (double)right, left.Unit); } public static double operator /(PowerRatio left, PowerRatio right) { // Logarithmic division = subtraction - return Convert.ToDouble(left._decibelWatts - right._decibelWatts); + return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); } #endif @@ -369,43 +384,43 @@ public int CompareTo(object obj) #endif int CompareTo(PowerRatio other) { - return _decibelWatts.CompareTo(other._decibelWatts); + return AsBaseUnitDecibelWatts().CompareTo(other.AsBaseUnitDecibelWatts()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(PowerRatio left, PowerRatio right) { - return left._decibelWatts <= right._decibelWatts; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(PowerRatio left, PowerRatio right) { - return left._decibelWatts >= right._decibelWatts; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(PowerRatio left, PowerRatio right) { - return left._decibelWatts < right._decibelWatts; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(PowerRatio left, PowerRatio right) { - return left._decibelWatts > right._decibelWatts; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(PowerRatio left, PowerRatio right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._decibelWatts == right._decibelWatts; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(PowerRatio left, PowerRatio right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._decibelWatts != right._decibelWatts; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -417,7 +432,7 @@ public override bool Equals(object obj) return false; } - return _decibelWatts.Equals(((PowerRatio) obj)._decibelWatts); + return AsBaseUnitDecibelWatts().Equals(((PowerRatio) obj).AsBaseUnitDecibelWatts()); } /// @@ -430,12 +445,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(PowerRatio other, PowerRatio maxError) { - return Math.Abs(_decibelWatts - other._decibelWatts) <= maxError._decibelWatts; + return Math.Abs(AsBaseUnitDecibelWatts() - other.AsBaseUnitDecibelWatts()) <= maxError.AsBaseUnitDecibelWatts(); } public override int GetHashCode() { - return _decibelWatts.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -445,16 +460,20 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(PowerRatioUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitDecibelWatts(); + switch (unit) { - case PowerRatioUnit.DecibelMilliwatt: - return DecibelMilliwatts; - case PowerRatioUnit.DecibelWatt: - return DecibelWatts; + case PowerRatioUnit.DecibelMilliwatt: return baseUnitValue + 30; + case PowerRatioUnit.DecibelWatt: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -496,7 +515,11 @@ public static PowerRatio Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -515,17 +538,24 @@ public static PowerRatio Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static PowerRatio Parse(string str, [CanBeNull] Culture culture) + public static PowerRatio Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -551,16 +581,41 @@ public static bool TryParse([CanBeNull] string str, out PowerRatio result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out PowerRatio result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out PowerRatio result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -573,6 +628,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -586,11 +642,14 @@ public static PowerRatioUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static PowerRatioUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -599,6 +658,8 @@ public static PowerRatioUnit ParseUnit(string str, [CanBeNull] string cultureNam /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -611,18 +672,18 @@ public static PowerRatioUnit ParseUnit(string str, [CanBeNull] string cultureNam #else public #endif - static PowerRatioUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static PowerRatioUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == PowerRatioUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PowerRatioUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -631,6 +692,7 @@ static PowerRatioUnit ParseUnit(string str, IFormatProvider formatProvider = nul #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is DecibelWatt /// @@ -642,7 +704,7 @@ static PowerRatioUnit ParseUnit(string str, IFormatProvider formatProvider = nul /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -659,74 +721,130 @@ public string ToString(PowerRatioUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(PowerRatioUnit unit, [CanBeNull] Culture culture) + public string ToString( + PowerRatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(PowerRatioUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + PowerRatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(PowerRatioUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + PowerRatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of PowerRatio /// - public static PowerRatio MaxValue - { - get - { - return new PowerRatio(double.MaxValue); - } - } + public static PowerRatio MaxValue => new PowerRatio(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of PowerRatio /// - public static PowerRatio MinValue + public static PowerRatio MinValue => new PowerRatio(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitDecibelWatts() { - get + if (Unit == PowerRatioUnit.DecibelWatt) { return _value; } + + switch (Unit) { - return new PowerRatio(double.MinValue); - } - } - } + case PowerRatioUnit.DecibelMilliwatt: return _value - 30; + case PowerRatioUnit.DecibelWatt: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(PowerRatioUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs index b592959f86..c30fa18350 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Pressure : IComparable, IComparable #endif { /// - /// Base unit of Pressure. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly PressureUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _pascals; + public PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Pressure() : this(0) + public Pressure() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Pressure(double pascals) { - _pascals = Convert.ToDouble(pascals); + _value = Convert.ToDouble(pascals); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Pressure(double numericValue, PressureUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Pascal. + /// + /// Value assuming base unit Pascal. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Pressure(long pascals) - { - _pascals = Convert.ToDouble(pascals); - } + Pressure(long pascals) : this(Convert.ToDouble(pascals), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Pascal. + /// + /// Value assuming base unit Pascal. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Pressure(decimal pascals) - { - _pascals = Convert.ToDouble(pascals); - } + Pressure(decimal pascals) : this(Convert.ToDouble(pascals), BaseUnit) { } #region Properties @@ -119,321 +156,167 @@ public Pressure(double pascals) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static PressureUnit BaseUnit - { - get { return PressureUnit.Pascal; } - } + public static PressureUnit BaseUnit => PressureUnit.Pascal; /// /// All units of measurement for the Pressure quantity. /// public static PressureUnit[] Units { get; } = Enum.GetValues(typeof(PressureUnit)).Cast().ToArray(); - /// /// Get Pressure in Atmospheres. /// - public double Atmospheres - { - get { return _pascals/(1.01325*1e5); } - } - + public double Atmospheres => As(PressureUnit.Atmosphere); /// /// Get Pressure in Bars. /// - public double Bars - { - get { return _pascals/1e5; } - } - + public double Bars => As(PressureUnit.Bar); /// /// Get Pressure in Centibars. /// - public double Centibars - { - get { return (_pascals/1e5) / 1e-2d; } - } - + public double Centibars => As(PressureUnit.Centibar); /// /// Get Pressure in Decapascals. /// - public double Decapascals - { - get { return (_pascals) / 1e1d; } - } - + public double Decapascals => As(PressureUnit.Decapascal); /// /// Get Pressure in Decibars. /// - public double Decibars - { - get { return (_pascals/1e5) / 1e-1d; } - } - + public double Decibars => As(PressureUnit.Decibar); /// /// Get Pressure in FeetOfHead. /// - public double FeetOfHead - { - get { return _pascals*0.000334552565551; } - } - + public double FeetOfHead => As(PressureUnit.FootOfHead); /// /// Get Pressure in Gigapascals. /// - public double Gigapascals - { - get { return (_pascals) / 1e9d; } - } - + public double Gigapascals => As(PressureUnit.Gigapascal); /// /// Get Pressure in Hectopascals. /// - public double Hectopascals - { - get { return (_pascals) / 1e2d; } - } - + public double Hectopascals => As(PressureUnit.Hectopascal); /// /// Get Pressure in InchesOfMercury. /// - public double InchesOfMercury - { - get { return _pascals*2.95299830714159e-4; } - } - + public double InchesOfMercury => As(PressureUnit.InchOfMercury); /// /// Get Pressure in Kilobars. /// - public double Kilobars - { - get { return (_pascals/1e5) / 1e3d; } - } - + public double Kilobars => As(PressureUnit.Kilobar); /// /// Get Pressure in KilogramsForcePerSquareCentimeter. /// - public double KilogramsForcePerSquareCentimeter - { - get { return _pascals/(9.80665*1e4); } - } - + public double KilogramsForcePerSquareCentimeter => As(PressureUnit.KilogramForcePerSquareCentimeter); /// /// Get Pressure in KilogramsForcePerSquareMeter. /// - public double KilogramsForcePerSquareMeter - { - get { return _pascals*0.101971619222242; } - } - + public double KilogramsForcePerSquareMeter => As(PressureUnit.KilogramForcePerSquareMeter); /// /// Get Pressure in KilogramsForcePerSquareMillimeter. /// - public double KilogramsForcePerSquareMillimeter - { - get { return _pascals*1.01971619222242E-07; } - } - + public double KilogramsForcePerSquareMillimeter => As(PressureUnit.KilogramForcePerSquareMillimeter); /// /// Get Pressure in KilonewtonsPerSquareCentimeter. /// - public double KilonewtonsPerSquareCentimeter - { - get { return (_pascals/1e4) / 1e3d; } - } - + public double KilonewtonsPerSquareCentimeter => As(PressureUnit.KilonewtonPerSquareCentimeter); /// /// Get Pressure in KilonewtonsPerSquareMeter. /// - public double KilonewtonsPerSquareMeter - { - get { return (_pascals) / 1e3d; } - } - + public double KilonewtonsPerSquareMeter => As(PressureUnit.KilonewtonPerSquareMeter); /// /// Get Pressure in KilonewtonsPerSquareMillimeter. /// - public double KilonewtonsPerSquareMillimeter - { - get { return (_pascals/1e6) / 1e3d; } - } - + public double KilonewtonsPerSquareMillimeter => As(PressureUnit.KilonewtonPerSquareMillimeter); /// /// Get Pressure in Kilopascals. /// - public double Kilopascals - { - get { return (_pascals) / 1e3d; } - } - + public double Kilopascals => As(PressureUnit.Kilopascal); /// /// Get Pressure in KilopoundsForcePerSquareFoot. /// - public double KilopoundsForcePerSquareFoot - { - get { return (_pascals*0.020885432426709) / 1e3d; } - } - + public double KilopoundsForcePerSquareFoot => As(PressureUnit.KilopoundForcePerSquareFoot); /// /// Get Pressure in KilopoundsForcePerSquareInch. /// - public double KilopoundsForcePerSquareInch - { - get { return (_pascals*0.000145037737730209) / 1e3d; } - } - + public double KilopoundsForcePerSquareInch => As(PressureUnit.KilopoundForcePerSquareInch); /// /// Get Pressure in Megabars. /// - public double Megabars - { - get { return (_pascals/1e5) / 1e6d; } - } - + public double Megabars => As(PressureUnit.Megabar); /// /// Get Pressure in Megapascals. /// - public double Megapascals - { - get { return (_pascals) / 1e6d; } - } - + public double Megapascals => As(PressureUnit.Megapascal); /// /// Get Pressure in MetersOfHead. /// - public double MetersOfHead - { - get { return _pascals*0.0001019977334; } - } - + public double MetersOfHead => As(PressureUnit.MeterOfHead); /// /// Get Pressure in Micropascals. /// - public double Micropascals - { - get { return (_pascals) / 1e-6d; } - } - + public double Micropascals => As(PressureUnit.Micropascal); /// /// Get Pressure in Millibars. /// - public double Millibars - { - get { return (_pascals/1e5) / 1e-3d; } - } - + public double Millibars => As(PressureUnit.Millibar); /// /// Get Pressure in MillimetersOfMercury. /// - public double MillimetersOfMercury - { - get { return _pascals*7.50061561302643e-3; } - } - + public double MillimetersOfMercury => As(PressureUnit.MillimeterOfMercury); /// /// Get Pressure in NewtonsPerSquareCentimeter. /// - public double NewtonsPerSquareCentimeter - { - get { return _pascals/1e4; } - } - + public double NewtonsPerSquareCentimeter => As(PressureUnit.NewtonPerSquareCentimeter); /// /// Get Pressure in NewtonsPerSquareMeter. /// - public double NewtonsPerSquareMeter - { - get { return _pascals; } - } - + public double NewtonsPerSquareMeter => As(PressureUnit.NewtonPerSquareMeter); /// /// Get Pressure in NewtonsPerSquareMillimeter. /// - public double NewtonsPerSquareMillimeter - { - get { return _pascals/1e6; } - } - + public double NewtonsPerSquareMillimeter => As(PressureUnit.NewtonPerSquareMillimeter); /// /// Get Pressure in Pascals. /// - public double Pascals - { - get { return _pascals; } - } - + public double Pascals => As(PressureUnit.Pascal); /// /// Get Pressure in PoundsForcePerSquareFoot. /// - public double PoundsForcePerSquareFoot - { - get { return _pascals*0.020885432426709; } - } - + public double PoundsForcePerSquareFoot => As(PressureUnit.PoundForcePerSquareFoot); /// /// Get Pressure in PoundsForcePerSquareInch. /// - public double PoundsForcePerSquareInch - { - get { return _pascals*0.000145037737730209; } - } - + public double PoundsForcePerSquareInch => As(PressureUnit.PoundForcePerSquareInch); /// /// Get Pressure in Psi. /// [System.Obsolete("Deprecated due to github issue #215, please use PoundForcePerSquareInch instead")] - public double Psi - { - get { return _pascals/(6.89464975179*1e3); } - } - + public double Psi => As(PressureUnit.Psi); /// /// Get Pressure in TechnicalAtmospheres. /// - public double TechnicalAtmospheres - { - get { return _pascals/(9.80680592331*1e4); } - } - + public double TechnicalAtmospheres => As(PressureUnit.TechnicalAtmosphere); /// /// Get Pressure in TonnesForcePerSquareCentimeter. /// - public double TonnesForcePerSquareCentimeter - { - get { return _pascals*1.01971619222242E-08; } - } - + public double TonnesForcePerSquareCentimeter => As(PressureUnit.TonneForcePerSquareCentimeter); /// /// Get Pressure in TonnesForcePerSquareMeter. /// - public double TonnesForcePerSquareMeter - { - get { return _pascals*0.000101971619222242; } - } - + public double TonnesForcePerSquareMeter => As(PressureUnit.TonneForcePerSquareMeter); /// /// Get Pressure in TonnesForcePerSquareMillimeter. /// - public double TonnesForcePerSquareMillimeter - { - get { return _pascals*1.01971619222242E-10; } - } - + public double TonnesForcePerSquareMillimeter => As(PressureUnit.TonneForcePerSquareMillimeter); /// /// Get Pressure in Torrs. /// - public double Torrs - { - get { return _pascals/(1.3332266752*1e2); } - } + public double Torrs => As(PressureUnit.Torr); #endregion #region Static - public static Pressure Zero - { - get { return new Pressure(); } - } + public static Pressure Zero => new Pressure(0, BaseUnit); /// /// Get Pressure from Atmospheres. @@ -441,17 +324,13 @@ public static Pressure Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromAtmospheres(double atmospheres) - { - double value = (double) atmospheres; - return new Pressure(value*1.01325*1e5); - } #else public static Pressure FromAtmospheres(QuantityValue atmospheres) +#endif { double value = (double) atmospheres; - return new Pressure((value*1.01325*1e5)); + return new Pressure(value, PressureUnit.Atmosphere); } -#endif /// /// Get Pressure from Bars. @@ -459,17 +338,13 @@ public static Pressure FromAtmospheres(QuantityValue atmospheres) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromBars(double bars) - { - double value = (double) bars; - return new Pressure(value*1e5); - } #else public static Pressure FromBars(QuantityValue bars) +#endif { double value = (double) bars; - return new Pressure((value*1e5)); + return new Pressure(value, PressureUnit.Bar); } -#endif /// /// Get Pressure from Centibars. @@ -477,17 +352,13 @@ public static Pressure FromBars(QuantityValue bars) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromCentibars(double centibars) - { - double value = (double) centibars; - return new Pressure((value*1e5) * 1e-2d); - } #else public static Pressure FromCentibars(QuantityValue centibars) +#endif { double value = (double) centibars; - return new Pressure(((value*1e5) * 1e-2d)); + return new Pressure(value, PressureUnit.Centibar); } -#endif /// /// Get Pressure from Decapascals. @@ -495,17 +366,13 @@ public static Pressure FromCentibars(QuantityValue centibars) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromDecapascals(double decapascals) - { - double value = (double) decapascals; - return new Pressure((value) * 1e1d); - } #else public static Pressure FromDecapascals(QuantityValue decapascals) +#endif { double value = (double) decapascals; - return new Pressure(((value) * 1e1d)); + return new Pressure(value, PressureUnit.Decapascal); } -#endif /// /// Get Pressure from Decibars. @@ -513,17 +380,13 @@ public static Pressure FromDecapascals(QuantityValue decapascals) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromDecibars(double decibars) - { - double value = (double) decibars; - return new Pressure((value*1e5) * 1e-1d); - } #else public static Pressure FromDecibars(QuantityValue decibars) +#endif { double value = (double) decibars; - return new Pressure(((value*1e5) * 1e-1d)); + return new Pressure(value, PressureUnit.Decibar); } -#endif /// /// Get Pressure from FeetOfHead. @@ -531,17 +394,13 @@ public static Pressure FromDecibars(QuantityValue decibars) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromFeetOfHead(double feetofhead) - { - double value = (double) feetofhead; - return new Pressure(value*2989.0669); - } #else public static Pressure FromFeetOfHead(QuantityValue feetofhead) +#endif { double value = (double) feetofhead; - return new Pressure((value*2989.0669)); + return new Pressure(value, PressureUnit.FootOfHead); } -#endif /// /// Get Pressure from Gigapascals. @@ -549,17 +408,13 @@ public static Pressure FromFeetOfHead(QuantityValue feetofhead) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromGigapascals(double gigapascals) - { - double value = (double) gigapascals; - return new Pressure((value) * 1e9d); - } #else public static Pressure FromGigapascals(QuantityValue gigapascals) +#endif { double value = (double) gigapascals; - return new Pressure(((value) * 1e9d)); + return new Pressure(value, PressureUnit.Gigapascal); } -#endif /// /// Get Pressure from Hectopascals. @@ -567,17 +422,13 @@ public static Pressure FromGigapascals(QuantityValue gigapascals) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromHectopascals(double hectopascals) - { - double value = (double) hectopascals; - return new Pressure((value) * 1e2d); - } #else public static Pressure FromHectopascals(QuantityValue hectopascals) +#endif { double value = (double) hectopascals; - return new Pressure(((value) * 1e2d)); + return new Pressure(value, PressureUnit.Hectopascal); } -#endif /// /// Get Pressure from InchesOfMercury. @@ -585,17 +436,13 @@ public static Pressure FromHectopascals(QuantityValue hectopascals) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromInchesOfMercury(double inchesofmercury) - { - double value = (double) inchesofmercury; - return new Pressure(value/2.95299830714159e-4); - } #else public static Pressure FromInchesOfMercury(QuantityValue inchesofmercury) +#endif { double value = (double) inchesofmercury; - return new Pressure((value/2.95299830714159e-4)); + return new Pressure(value, PressureUnit.InchOfMercury); } -#endif /// /// Get Pressure from Kilobars. @@ -603,17 +450,13 @@ public static Pressure FromInchesOfMercury(QuantityValue inchesofmercury) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromKilobars(double kilobars) - { - double value = (double) kilobars; - return new Pressure((value*1e5) * 1e3d); - } #else public static Pressure FromKilobars(QuantityValue kilobars) +#endif { double value = (double) kilobars; - return new Pressure(((value*1e5) * 1e3d)); + return new Pressure(value, PressureUnit.Kilobar); } -#endif /// /// Get Pressure from KilogramsForcePerSquareCentimeter. @@ -621,17 +464,13 @@ public static Pressure FromKilobars(QuantityValue kilobars) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromKilogramsForcePerSquareCentimeter(double kilogramsforcepersquarecentimeter) - { - double value = (double) kilogramsforcepersquarecentimeter; - return new Pressure(value*9.80665*1e4); - } #else public static Pressure FromKilogramsForcePerSquareCentimeter(QuantityValue kilogramsforcepersquarecentimeter) +#endif { double value = (double) kilogramsforcepersquarecentimeter; - return new Pressure((value*9.80665*1e4)); + return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); } -#endif /// /// Get Pressure from KilogramsForcePerSquareMeter. @@ -639,17 +478,13 @@ public static Pressure FromKilogramsForcePerSquareCentimeter(QuantityValue kilog #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromKilogramsForcePerSquareMeter(double kilogramsforcepersquaremeter) - { - double value = (double) kilogramsforcepersquaremeter; - return new Pressure(value*9.80665019960652); - } #else public static Pressure FromKilogramsForcePerSquareMeter(QuantityValue kilogramsforcepersquaremeter) +#endif { double value = (double) kilogramsforcepersquaremeter; - return new Pressure((value*9.80665019960652)); + return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); } -#endif /// /// Get Pressure from KilogramsForcePerSquareMillimeter. @@ -657,17 +492,13 @@ public static Pressure FromKilogramsForcePerSquareMeter(QuantityValue kilogramsf #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromKilogramsForcePerSquareMillimeter(double kilogramsforcepersquaremillimeter) - { - double value = (double) kilogramsforcepersquaremillimeter; - return new Pressure(value*9806650.19960652); - } #else public static Pressure FromKilogramsForcePerSquareMillimeter(QuantityValue kilogramsforcepersquaremillimeter) +#endif { double value = (double) kilogramsforcepersquaremillimeter; - return new Pressure((value*9806650.19960652)); + return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); } -#endif /// /// Get Pressure from KilonewtonsPerSquareCentimeter. @@ -675,17 +506,13 @@ public static Pressure FromKilogramsForcePerSquareMillimeter(QuantityValue kilog #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromKilonewtonsPerSquareCentimeter(double kilonewtonspersquarecentimeter) - { - double value = (double) kilonewtonspersquarecentimeter; - return new Pressure((value*1e4) * 1e3d); - } #else public static Pressure FromKilonewtonsPerSquareCentimeter(QuantityValue kilonewtonspersquarecentimeter) +#endif { double value = (double) kilonewtonspersquarecentimeter; - return new Pressure(((value*1e4) * 1e3d)); + return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); } -#endif /// /// Get Pressure from KilonewtonsPerSquareMeter. @@ -693,17 +520,13 @@ public static Pressure FromKilonewtonsPerSquareCentimeter(QuantityValue kilonewt #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromKilonewtonsPerSquareMeter(double kilonewtonspersquaremeter) - { - double value = (double) kilonewtonspersquaremeter; - return new Pressure((value) * 1e3d); - } #else public static Pressure FromKilonewtonsPerSquareMeter(QuantityValue kilonewtonspersquaremeter) +#endif { double value = (double) kilonewtonspersquaremeter; - return new Pressure(((value) * 1e3d)); + return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); } -#endif /// /// Get Pressure from KilonewtonsPerSquareMillimeter. @@ -711,17 +534,13 @@ public static Pressure FromKilonewtonsPerSquareMeter(QuantityValue kilonewtonspe #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromKilonewtonsPerSquareMillimeter(double kilonewtonspersquaremillimeter) - { - double value = (double) kilonewtonspersquaremillimeter; - return new Pressure((value*1e6) * 1e3d); - } #else public static Pressure FromKilonewtonsPerSquareMillimeter(QuantityValue kilonewtonspersquaremillimeter) +#endif { double value = (double) kilonewtonspersquaremillimeter; - return new Pressure(((value*1e6) * 1e3d)); + return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); } -#endif /// /// Get Pressure from Kilopascals. @@ -729,17 +548,13 @@ public static Pressure FromKilonewtonsPerSquareMillimeter(QuantityValue kilonewt #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromKilopascals(double kilopascals) - { - double value = (double) kilopascals; - return new Pressure((value) * 1e3d); - } #else public static Pressure FromKilopascals(QuantityValue kilopascals) +#endif { double value = (double) kilopascals; - return new Pressure(((value) * 1e3d)); + return new Pressure(value, PressureUnit.Kilopascal); } -#endif /// /// Get Pressure from KilopoundsForcePerSquareFoot. @@ -747,17 +562,13 @@ public static Pressure FromKilopascals(QuantityValue kilopascals) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromKilopoundsForcePerSquareFoot(double kilopoundsforcepersquarefoot) - { - double value = (double) kilopoundsforcepersquarefoot; - return new Pressure((value*47.8802631216372) * 1e3d); - } #else public static Pressure FromKilopoundsForcePerSquareFoot(QuantityValue kilopoundsforcepersquarefoot) +#endif { double value = (double) kilopoundsforcepersquarefoot; - return new Pressure(((value*47.8802631216372) * 1e3d)); + return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); } -#endif /// /// Get Pressure from KilopoundsForcePerSquareInch. @@ -765,17 +576,13 @@ public static Pressure FromKilopoundsForcePerSquareFoot(QuantityValue kilopounds #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromKilopoundsForcePerSquareInch(double kilopoundsforcepersquareinch) - { - double value = (double) kilopoundsforcepersquareinch; - return new Pressure((value*6894.75729316836) * 1e3d); - } #else public static Pressure FromKilopoundsForcePerSquareInch(QuantityValue kilopoundsforcepersquareinch) +#endif { double value = (double) kilopoundsforcepersquareinch; - return new Pressure(((value*6894.75729316836) * 1e3d)); + return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); } -#endif /// /// Get Pressure from Megabars. @@ -783,17 +590,13 @@ public static Pressure FromKilopoundsForcePerSquareInch(QuantityValue kilopounds #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromMegabars(double megabars) - { - double value = (double) megabars; - return new Pressure((value*1e5) * 1e6d); - } #else public static Pressure FromMegabars(QuantityValue megabars) +#endif { double value = (double) megabars; - return new Pressure(((value*1e5) * 1e6d)); + return new Pressure(value, PressureUnit.Megabar); } -#endif /// /// Get Pressure from Megapascals. @@ -801,17 +604,13 @@ public static Pressure FromMegabars(QuantityValue megabars) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromMegapascals(double megapascals) - { - double value = (double) megapascals; - return new Pressure((value) * 1e6d); - } #else public static Pressure FromMegapascals(QuantityValue megapascals) +#endif { double value = (double) megapascals; - return new Pressure(((value) * 1e6d)); + return new Pressure(value, PressureUnit.Megapascal); } -#endif /// /// Get Pressure from MetersOfHead. @@ -819,17 +618,13 @@ public static Pressure FromMegapascals(QuantityValue megapascals) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromMetersOfHead(double metersofhead) - { - double value = (double) metersofhead; - return new Pressure(value*9804.139432); - } #else public static Pressure FromMetersOfHead(QuantityValue metersofhead) +#endif { double value = (double) metersofhead; - return new Pressure((value*9804.139432)); + return new Pressure(value, PressureUnit.MeterOfHead); } -#endif /// /// Get Pressure from Micropascals. @@ -837,17 +632,13 @@ public static Pressure FromMetersOfHead(QuantityValue metersofhead) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromMicropascals(double micropascals) - { - double value = (double) micropascals; - return new Pressure((value) * 1e-6d); - } #else public static Pressure FromMicropascals(QuantityValue micropascals) +#endif { double value = (double) micropascals; - return new Pressure(((value) * 1e-6d)); + return new Pressure(value, PressureUnit.Micropascal); } -#endif /// /// Get Pressure from Millibars. @@ -855,17 +646,13 @@ public static Pressure FromMicropascals(QuantityValue micropascals) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromMillibars(double millibars) - { - double value = (double) millibars; - return new Pressure((value*1e5) * 1e-3d); - } #else public static Pressure FromMillibars(QuantityValue millibars) +#endif { double value = (double) millibars; - return new Pressure(((value*1e5) * 1e-3d)); + return new Pressure(value, PressureUnit.Millibar); } -#endif /// /// Get Pressure from MillimetersOfMercury. @@ -873,17 +660,13 @@ public static Pressure FromMillibars(QuantityValue millibars) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromMillimetersOfMercury(double millimetersofmercury) - { - double value = (double) millimetersofmercury; - return new Pressure(value/7.50061561302643e-3); - } #else public static Pressure FromMillimetersOfMercury(QuantityValue millimetersofmercury) +#endif { double value = (double) millimetersofmercury; - return new Pressure((value/7.50061561302643e-3)); + return new Pressure(value, PressureUnit.MillimeterOfMercury); } -#endif /// /// Get Pressure from NewtonsPerSquareCentimeter. @@ -891,17 +674,13 @@ public static Pressure FromMillimetersOfMercury(QuantityValue millimetersofmercu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromNewtonsPerSquareCentimeter(double newtonspersquarecentimeter) - { - double value = (double) newtonspersquarecentimeter; - return new Pressure(value*1e4); - } #else public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue newtonspersquarecentimeter) +#endif { double value = (double) newtonspersquarecentimeter; - return new Pressure((value*1e4)); + return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); } -#endif /// /// Get Pressure from NewtonsPerSquareMeter. @@ -909,17 +688,13 @@ public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue newtonspersq #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromNewtonsPerSquareMeter(double newtonspersquaremeter) - { - double value = (double) newtonspersquaremeter; - return new Pressure(value); - } #else public static Pressure FromNewtonsPerSquareMeter(QuantityValue newtonspersquaremeter) +#endif { double value = (double) newtonspersquaremeter; - return new Pressure((value)); + return new Pressure(value, PressureUnit.NewtonPerSquareMeter); } -#endif /// /// Get Pressure from NewtonsPerSquareMillimeter. @@ -927,17 +702,13 @@ public static Pressure FromNewtonsPerSquareMeter(QuantityValue newtonspersquarem #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromNewtonsPerSquareMillimeter(double newtonspersquaremillimeter) - { - double value = (double) newtonspersquaremillimeter; - return new Pressure(value*1e6); - } #else public static Pressure FromNewtonsPerSquareMillimeter(QuantityValue newtonspersquaremillimeter) +#endif { double value = (double) newtonspersquaremillimeter; - return new Pressure((value*1e6)); + return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); } -#endif /// /// Get Pressure from Pascals. @@ -945,17 +716,13 @@ public static Pressure FromNewtonsPerSquareMillimeter(QuantityValue newtonspersq #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromPascals(double pascals) - { - double value = (double) pascals; - return new Pressure(value); - } #else public static Pressure FromPascals(QuantityValue pascals) +#endif { double value = (double) pascals; - return new Pressure((value)); + return new Pressure(value, PressureUnit.Pascal); } -#endif /// /// Get Pressure from PoundsForcePerSquareFoot. @@ -963,17 +730,13 @@ public static Pressure FromPascals(QuantityValue pascals) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromPoundsForcePerSquareFoot(double poundsforcepersquarefoot) - { - double value = (double) poundsforcepersquarefoot; - return new Pressure(value*47.8802631216372); - } #else public static Pressure FromPoundsForcePerSquareFoot(QuantityValue poundsforcepersquarefoot) +#endif { double value = (double) poundsforcepersquarefoot; - return new Pressure((value*47.8802631216372)); + return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); } -#endif /// /// Get Pressure from PoundsForcePerSquareInch. @@ -981,17 +744,13 @@ public static Pressure FromPoundsForcePerSquareFoot(QuantityValue poundsforceper #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromPoundsForcePerSquareInch(double poundsforcepersquareinch) - { - double value = (double) poundsforcepersquareinch; - return new Pressure(value*6894.75729316836); - } #else public static Pressure FromPoundsForcePerSquareInch(QuantityValue poundsforcepersquareinch) +#endif { double value = (double) poundsforcepersquareinch; - return new Pressure((value*6894.75729316836)); + return new Pressure(value, PressureUnit.PoundForcePerSquareInch); } -#endif /// /// Get Pressure from Psi. @@ -999,17 +758,13 @@ public static Pressure FromPoundsForcePerSquareInch(QuantityValue poundsforceper #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromPsi(double psi) - { - double value = (double) psi; - return new Pressure(value*6.89464975179*1e3); - } #else public static Pressure FromPsi(QuantityValue psi) +#endif { double value = (double) psi; - return new Pressure((value*6.89464975179*1e3)); + return new Pressure(value, PressureUnit.Psi); } -#endif /// /// Get Pressure from TechnicalAtmospheres. @@ -1017,17 +772,13 @@ public static Pressure FromPsi(QuantityValue psi) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromTechnicalAtmospheres(double technicalatmospheres) - { - double value = (double) technicalatmospheres; - return new Pressure(value*9.80680592331*1e4); - } #else public static Pressure FromTechnicalAtmospheres(QuantityValue technicalatmospheres) +#endif { double value = (double) technicalatmospheres; - return new Pressure((value*9.80680592331*1e4)); + return new Pressure(value, PressureUnit.TechnicalAtmosphere); } -#endif /// /// Get Pressure from TonnesForcePerSquareCentimeter. @@ -1035,17 +786,13 @@ public static Pressure FromTechnicalAtmospheres(QuantityValue technicalatmospher #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromTonnesForcePerSquareCentimeter(double tonnesforcepersquarecentimeter) - { - double value = (double) tonnesforcepersquarecentimeter; - return new Pressure(value*98066501.9960652); - } #else public static Pressure FromTonnesForcePerSquareCentimeter(QuantityValue tonnesforcepersquarecentimeter) +#endif { double value = (double) tonnesforcepersquarecentimeter; - return new Pressure((value*98066501.9960652)); + return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); } -#endif /// /// Get Pressure from TonnesForcePerSquareMeter. @@ -1053,17 +800,13 @@ public static Pressure FromTonnesForcePerSquareCentimeter(QuantityValue tonnesfo #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromTonnesForcePerSquareMeter(double tonnesforcepersquaremeter) - { - double value = (double) tonnesforcepersquaremeter; - return new Pressure(value*9806.65019960653); - } #else public static Pressure FromTonnesForcePerSquareMeter(QuantityValue tonnesforcepersquaremeter) +#endif { double value = (double) tonnesforcepersquaremeter; - return new Pressure((value*9806.65019960653)); + return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); } -#endif /// /// Get Pressure from TonnesForcePerSquareMillimeter. @@ -1071,17 +814,13 @@ public static Pressure FromTonnesForcePerSquareMeter(QuantityValue tonnesforcepe #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromTonnesForcePerSquareMillimeter(double tonnesforcepersquaremillimeter) - { - double value = (double) tonnesforcepersquaremillimeter; - return new Pressure(value*9806650199.60653); - } #else public static Pressure FromTonnesForcePerSquareMillimeter(QuantityValue tonnesforcepersquaremillimeter) +#endif { double value = (double) tonnesforcepersquaremillimeter; - return new Pressure((value*9806650199.60653)); + return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); } -#endif /// /// Get Pressure from Torrs. @@ -1089,17 +828,13 @@ public static Pressure FromTonnesForcePerSquareMillimeter(QuantityValue tonnesfo #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Pressure FromTorrs(double torrs) - { - double value = (double) torrs; - return new Pressure(value*1.3332266752*1e2); - } #else public static Pressure FromTorrs(QuantityValue torrs) +#endif { double value = (double) torrs; - return new Pressure((value*1.3332266752*1e2)); + return new Pressure(value, PressureUnit.Torr); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1674,86 +1409,7 @@ public static Pressure From(double value, PressureUnit fromUnit) public static Pressure From(QuantityValue value, PressureUnit fromUnit) #endif { - switch (fromUnit) - { - case PressureUnit.Atmosphere: - return FromAtmospheres(value); - case PressureUnit.Bar: - return FromBars(value); - case PressureUnit.Centibar: - return FromCentibars(value); - case PressureUnit.Decapascal: - return FromDecapascals(value); - case PressureUnit.Decibar: - return FromDecibars(value); - case PressureUnit.FootOfHead: - return FromFeetOfHead(value); - case PressureUnit.Gigapascal: - return FromGigapascals(value); - case PressureUnit.Hectopascal: - return FromHectopascals(value); - case PressureUnit.InchOfMercury: - return FromInchesOfMercury(value); - case PressureUnit.Kilobar: - return FromKilobars(value); - case PressureUnit.KilogramForcePerSquareCentimeter: - return FromKilogramsForcePerSquareCentimeter(value); - case PressureUnit.KilogramForcePerSquareMeter: - return FromKilogramsForcePerSquareMeter(value); - case PressureUnit.KilogramForcePerSquareMillimeter: - return FromKilogramsForcePerSquareMillimeter(value); - case PressureUnit.KilonewtonPerSquareCentimeter: - return FromKilonewtonsPerSquareCentimeter(value); - case PressureUnit.KilonewtonPerSquareMeter: - return FromKilonewtonsPerSquareMeter(value); - case PressureUnit.KilonewtonPerSquareMillimeter: - return FromKilonewtonsPerSquareMillimeter(value); - case PressureUnit.Kilopascal: - return FromKilopascals(value); - case PressureUnit.KilopoundForcePerSquareFoot: - return FromKilopoundsForcePerSquareFoot(value); - case PressureUnit.KilopoundForcePerSquareInch: - return FromKilopoundsForcePerSquareInch(value); - case PressureUnit.Megabar: - return FromMegabars(value); - case PressureUnit.Megapascal: - return FromMegapascals(value); - case PressureUnit.MeterOfHead: - return FromMetersOfHead(value); - case PressureUnit.Micropascal: - return FromMicropascals(value); - case PressureUnit.Millibar: - return FromMillibars(value); - case PressureUnit.MillimeterOfMercury: - return FromMillimetersOfMercury(value); - case PressureUnit.NewtonPerSquareCentimeter: - return FromNewtonsPerSquareCentimeter(value); - case PressureUnit.NewtonPerSquareMeter: - return FromNewtonsPerSquareMeter(value); - case PressureUnit.NewtonPerSquareMillimeter: - return FromNewtonsPerSquareMillimeter(value); - case PressureUnit.Pascal: - return FromPascals(value); - case PressureUnit.PoundForcePerSquareFoot: - return FromPoundsForcePerSquareFoot(value); - case PressureUnit.PoundForcePerSquareInch: - return FromPoundsForcePerSquareInch(value); - case PressureUnit.Psi: - return FromPsi(value); - case PressureUnit.TechnicalAtmosphere: - return FromTechnicalAtmospheres(value); - case PressureUnit.TonneForcePerSquareCentimeter: - return FromTonnesForcePerSquareCentimeter(value); - case PressureUnit.TonneForcePerSquareMeter: - return FromTonnesForcePerSquareMeter(value); - case PressureUnit.TonneForcePerSquareMillimeter: - return FromTonnesForcePerSquareMillimeter(value); - case PressureUnit.Torr: - return FromTorrs(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Pressure((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1770,86 +1426,8 @@ public static Pressure From(QuantityValue value, PressureUnit fromUnit) { return null; } - switch (fromUnit) - { - case PressureUnit.Atmosphere: - return FromAtmospheres(value.Value); - case PressureUnit.Bar: - return FromBars(value.Value); - case PressureUnit.Centibar: - return FromCentibars(value.Value); - case PressureUnit.Decapascal: - return FromDecapascals(value.Value); - case PressureUnit.Decibar: - return FromDecibars(value.Value); - case PressureUnit.FootOfHead: - return FromFeetOfHead(value.Value); - case PressureUnit.Gigapascal: - return FromGigapascals(value.Value); - case PressureUnit.Hectopascal: - return FromHectopascals(value.Value); - case PressureUnit.InchOfMercury: - return FromInchesOfMercury(value.Value); - case PressureUnit.Kilobar: - return FromKilobars(value.Value); - case PressureUnit.KilogramForcePerSquareCentimeter: - return FromKilogramsForcePerSquareCentimeter(value.Value); - case PressureUnit.KilogramForcePerSquareMeter: - return FromKilogramsForcePerSquareMeter(value.Value); - case PressureUnit.KilogramForcePerSquareMillimeter: - return FromKilogramsForcePerSquareMillimeter(value.Value); - case PressureUnit.KilonewtonPerSquareCentimeter: - return FromKilonewtonsPerSquareCentimeter(value.Value); - case PressureUnit.KilonewtonPerSquareMeter: - return FromKilonewtonsPerSquareMeter(value.Value); - case PressureUnit.KilonewtonPerSquareMillimeter: - return FromKilonewtonsPerSquareMillimeter(value.Value); - case PressureUnit.Kilopascal: - return FromKilopascals(value.Value); - case PressureUnit.KilopoundForcePerSquareFoot: - return FromKilopoundsForcePerSquareFoot(value.Value); - case PressureUnit.KilopoundForcePerSquareInch: - return FromKilopoundsForcePerSquareInch(value.Value); - case PressureUnit.Megabar: - return FromMegabars(value.Value); - case PressureUnit.Megapascal: - return FromMegapascals(value.Value); - case PressureUnit.MeterOfHead: - return FromMetersOfHead(value.Value); - case PressureUnit.Micropascal: - return FromMicropascals(value.Value); - case PressureUnit.Millibar: - return FromMillibars(value.Value); - case PressureUnit.MillimeterOfMercury: - return FromMillimetersOfMercury(value.Value); - case PressureUnit.NewtonPerSquareCentimeter: - return FromNewtonsPerSquareCentimeter(value.Value); - case PressureUnit.NewtonPerSquareMeter: - return FromNewtonsPerSquareMeter(value.Value); - case PressureUnit.NewtonPerSquareMillimeter: - return FromNewtonsPerSquareMillimeter(value.Value); - case PressureUnit.Pascal: - return FromPascals(value.Value); - case PressureUnit.PoundForcePerSquareFoot: - return FromPoundsForcePerSquareFoot(value.Value); - case PressureUnit.PoundForcePerSquareInch: - return FromPoundsForcePerSquareInch(value.Value); - case PressureUnit.Psi: - return FromPsi(value.Value); - case PressureUnit.TechnicalAtmosphere: - return FromTechnicalAtmospheres(value.Value); - case PressureUnit.TonneForcePerSquareCentimeter: - return FromTonnesForcePerSquareCentimeter(value.Value); - case PressureUnit.TonneForcePerSquareMeter: - return FromTonnesForcePerSquareMeter(value.Value); - case PressureUnit.TonneForcePerSquareMillimeter: - return FromTonnesForcePerSquareMillimeter(value.Value); - case PressureUnit.Torr: - return FromTorrs(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Pressure((double)value.Value, fromUnit); } #endif @@ -1868,12 +1446,29 @@ public static string GetAbbreviation(PressureUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(PressureUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + PressureUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1884,37 +1479,37 @@ public static string GetAbbreviation(PressureUnit unit, [CanBeNull] Culture cult #if !WINDOWS_UWP public static Pressure operator -(Pressure right) { - return new Pressure(-right._pascals); + return new Pressure(-right.Value, right.Unit); } public static Pressure operator +(Pressure left, Pressure right) { - return new Pressure(left._pascals + right._pascals); + return new Pressure(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Pressure operator -(Pressure left, Pressure right) { - return new Pressure(left._pascals - right._pascals); + return new Pressure(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Pressure operator *(double left, Pressure right) { - return new Pressure(left*right._pascals); + return new Pressure(left * right.Value, right.Unit); } public static Pressure operator *(Pressure left, double right) { - return new Pressure(left._pascals*(double)right); + return new Pressure(left.Value * right, left.Unit); } public static Pressure operator /(Pressure left, double right) { - return new Pressure(left._pascals/(double)right); + return new Pressure(left.Value / right, left.Unit); } public static double operator /(Pressure left, Pressure right) { - return Convert.ToDouble(left._pascals/right._pascals); + return left.Pascals / right.Pascals; } #endif @@ -1937,43 +1532,43 @@ public int CompareTo(object obj) #endif int CompareTo(Pressure other) { - return _pascals.CompareTo(other._pascals); + return AsBaseUnitPascals().CompareTo(other.AsBaseUnitPascals()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Pressure left, Pressure right) { - return left._pascals <= right._pascals; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Pressure left, Pressure right) { - return left._pascals >= right._pascals; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Pressure left, Pressure right) { - return left._pascals < right._pascals; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Pressure left, Pressure right) { - return left._pascals > right._pascals; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Pressure left, Pressure right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._pascals == right._pascals; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Pressure left, Pressure right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._pascals != right._pascals; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1985,7 +1580,7 @@ public override bool Equals(object obj) return false; } - return _pascals.Equals(((Pressure) obj)._pascals); + return AsBaseUnitPascals().Equals(((Pressure) obj).AsBaseUnitPascals()); } /// @@ -1998,12 +1593,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Pressure other, Pressure maxError) { - return Math.Abs(_pascals - other._pascals) <= maxError._pascals; + return Math.Abs(AsBaseUnitPascals() - other.AsBaseUnitPascals()) <= maxError.AsBaseUnitPascals(); } public override int GetHashCode() { - return _pascals.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -2013,86 +1608,55 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(PressureUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitPascals(); + switch (unit) { - case PressureUnit.Atmosphere: - return Atmospheres; - case PressureUnit.Bar: - return Bars; - case PressureUnit.Centibar: - return Centibars; - case PressureUnit.Decapascal: - return Decapascals; - case PressureUnit.Decibar: - return Decibars; - case PressureUnit.FootOfHead: - return FeetOfHead; - case PressureUnit.Gigapascal: - return Gigapascals; - case PressureUnit.Hectopascal: - return Hectopascals; - case PressureUnit.InchOfMercury: - return InchesOfMercury; - case PressureUnit.Kilobar: - return Kilobars; - case PressureUnit.KilogramForcePerSquareCentimeter: - return KilogramsForcePerSquareCentimeter; - case PressureUnit.KilogramForcePerSquareMeter: - return KilogramsForcePerSquareMeter; - case PressureUnit.KilogramForcePerSquareMillimeter: - return KilogramsForcePerSquareMillimeter; - case PressureUnit.KilonewtonPerSquareCentimeter: - return KilonewtonsPerSquareCentimeter; - case PressureUnit.KilonewtonPerSquareMeter: - return KilonewtonsPerSquareMeter; - case PressureUnit.KilonewtonPerSquareMillimeter: - return KilonewtonsPerSquareMillimeter; - case PressureUnit.Kilopascal: - return Kilopascals; - case PressureUnit.KilopoundForcePerSquareFoot: - return KilopoundsForcePerSquareFoot; - case PressureUnit.KilopoundForcePerSquareInch: - return KilopoundsForcePerSquareInch; - case PressureUnit.Megabar: - return Megabars; - case PressureUnit.Megapascal: - return Megapascals; - case PressureUnit.MeterOfHead: - return MetersOfHead; - case PressureUnit.Micropascal: - return Micropascals; - case PressureUnit.Millibar: - return Millibars; - case PressureUnit.MillimeterOfMercury: - return MillimetersOfMercury; - case PressureUnit.NewtonPerSquareCentimeter: - return NewtonsPerSquareCentimeter; - case PressureUnit.NewtonPerSquareMeter: - return NewtonsPerSquareMeter; - case PressureUnit.NewtonPerSquareMillimeter: - return NewtonsPerSquareMillimeter; - case PressureUnit.Pascal: - return Pascals; - case PressureUnit.PoundForcePerSquareFoot: - return PoundsForcePerSquareFoot; - case PressureUnit.PoundForcePerSquareInch: - return PoundsForcePerSquareInch; - case PressureUnit.Psi: - return Psi; - case PressureUnit.TechnicalAtmosphere: - return TechnicalAtmospheres; - case PressureUnit.TonneForcePerSquareCentimeter: - return TonnesForcePerSquareCentimeter; - case PressureUnit.TonneForcePerSquareMeter: - return TonnesForcePerSquareMeter; - case PressureUnit.TonneForcePerSquareMillimeter: - return TonnesForcePerSquareMillimeter; - case PressureUnit.Torr: - return Torrs; + case PressureUnit.Atmosphere: return baseUnitValue/(1.01325*1e5); + case PressureUnit.Bar: return baseUnitValue/1e5; + case PressureUnit.Centibar: return (baseUnitValue/1e5) / 1e-2d; + case PressureUnit.Decapascal: return (baseUnitValue) / 1e1d; + case PressureUnit.Decibar: return (baseUnitValue/1e5) / 1e-1d; + case PressureUnit.FootOfHead: return baseUnitValue*0.000334552565551; + case PressureUnit.Gigapascal: return (baseUnitValue) / 1e9d; + case PressureUnit.Hectopascal: return (baseUnitValue) / 1e2d; + case PressureUnit.InchOfMercury: return baseUnitValue*2.95299830714159e-4; + case PressureUnit.Kilobar: return (baseUnitValue/1e5) / 1e3d; + case PressureUnit.KilogramForcePerSquareCentimeter: return baseUnitValue/(9.80665*1e4); + case PressureUnit.KilogramForcePerSquareMeter: return baseUnitValue*0.101971619222242; + case PressureUnit.KilogramForcePerSquareMillimeter: return baseUnitValue*1.01971619222242E-07; + case PressureUnit.KilonewtonPerSquareCentimeter: return (baseUnitValue/1e4) / 1e3d; + case PressureUnit.KilonewtonPerSquareMeter: return (baseUnitValue) / 1e3d; + case PressureUnit.KilonewtonPerSquareMillimeter: return (baseUnitValue/1e6) / 1e3d; + case PressureUnit.Kilopascal: return (baseUnitValue) / 1e3d; + case PressureUnit.KilopoundForcePerSquareFoot: return (baseUnitValue*0.020885432426709) / 1e3d; + case PressureUnit.KilopoundForcePerSquareInch: return (baseUnitValue*0.000145037737730209) / 1e3d; + case PressureUnit.Megabar: return (baseUnitValue/1e5) / 1e6d; + case PressureUnit.Megapascal: return (baseUnitValue) / 1e6d; + case PressureUnit.MeterOfHead: return baseUnitValue*0.0001019977334; + case PressureUnit.Micropascal: return (baseUnitValue) / 1e-6d; + case PressureUnit.Millibar: return (baseUnitValue/1e5) / 1e-3d; + case PressureUnit.MillimeterOfMercury: return baseUnitValue*7.50061561302643e-3; + case PressureUnit.NewtonPerSquareCentimeter: return baseUnitValue/1e4; + case PressureUnit.NewtonPerSquareMeter: return baseUnitValue; + case PressureUnit.NewtonPerSquareMillimeter: return baseUnitValue/1e6; + case PressureUnit.Pascal: return baseUnitValue; + case PressureUnit.PoundForcePerSquareFoot: return baseUnitValue*0.020885432426709; + case PressureUnit.PoundForcePerSquareInch: return baseUnitValue*0.000145037737730209; + case PressureUnit.Psi: return baseUnitValue/(6.89464975179*1e3); + case PressureUnit.TechnicalAtmosphere: return baseUnitValue/(9.80680592331*1e4); + case PressureUnit.TonneForcePerSquareCentimeter: return baseUnitValue*1.01971619222242E-08; + case PressureUnit.TonneForcePerSquareMeter: return baseUnitValue*0.000101971619222242; + case PressureUnit.TonneForcePerSquareMillimeter: return baseUnitValue*1.01971619222242E-10; + case PressureUnit.Torr: return baseUnitValue/(1.3332266752*1e2); default: throw new NotImplementedException("unit: " + unit); @@ -2134,7 +1698,11 @@ public static Pressure Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -2153,17 +1721,24 @@ public static Pressure Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Pressure Parse(string str, [CanBeNull] Culture culture) + public static Pressure Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -2189,16 +1764,41 @@ public static bool TryParse([CanBeNull] string str, out Pressure result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Pressure result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Pressure result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -2211,6 +1811,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -2224,11 +1825,14 @@ public static PressureUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static PressureUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -2237,6 +1841,8 @@ public static PressureUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -2249,18 +1855,18 @@ public static PressureUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static PressureUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static PressureUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == PressureUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PressureUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -2269,6 +1875,7 @@ static PressureUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Pascal /// @@ -2280,7 +1887,7 @@ static PressureUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -2297,74 +1904,165 @@ public string ToString(PressureUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(PressureUnit unit, [CanBeNull] Culture culture) + public string ToString( + PressureUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(PressureUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + PressureUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(PressureUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + PressureUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Pressure /// - public static Pressure MaxValue - { - get - { - return new Pressure(double.MaxValue); - } - } + public static Pressure MaxValue => new Pressure(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Pressure /// - public static Pressure MinValue - { - get - { - return new Pressure(double.MinValue); - } - } - } + public static Pressure MinValue => new Pressure(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitPascals() + { + if (Unit == PressureUnit.Pascal) { return _value; } + + switch (Unit) + { + case PressureUnit.Atmosphere: return _value*1.01325*1e5; + case PressureUnit.Bar: return _value*1e5; + case PressureUnit.Centibar: return (_value*1e5) * 1e-2d; + case PressureUnit.Decapascal: return (_value) * 1e1d; + case PressureUnit.Decibar: return (_value*1e5) * 1e-1d; + case PressureUnit.FootOfHead: return _value*2989.0669; + case PressureUnit.Gigapascal: return (_value) * 1e9d; + case PressureUnit.Hectopascal: return (_value) * 1e2d; + case PressureUnit.InchOfMercury: return _value/2.95299830714159e-4; + case PressureUnit.Kilobar: return (_value*1e5) * 1e3d; + case PressureUnit.KilogramForcePerSquareCentimeter: return _value*9.80665*1e4; + case PressureUnit.KilogramForcePerSquareMeter: return _value*9.80665019960652; + case PressureUnit.KilogramForcePerSquareMillimeter: return _value*9806650.19960652; + case PressureUnit.KilonewtonPerSquareCentimeter: return (_value*1e4) * 1e3d; + case PressureUnit.KilonewtonPerSquareMeter: return (_value) * 1e3d; + case PressureUnit.KilonewtonPerSquareMillimeter: return (_value*1e6) * 1e3d; + case PressureUnit.Kilopascal: return (_value) * 1e3d; + case PressureUnit.KilopoundForcePerSquareFoot: return (_value*47.8802631216372) * 1e3d; + case PressureUnit.KilopoundForcePerSquareInch: return (_value*6894.75729316836) * 1e3d; + case PressureUnit.Megabar: return (_value*1e5) * 1e6d; + case PressureUnit.Megapascal: return (_value) * 1e6d; + case PressureUnit.MeterOfHead: return _value*9804.139432; + case PressureUnit.Micropascal: return (_value) * 1e-6d; + case PressureUnit.Millibar: return (_value*1e5) * 1e-3d; + case PressureUnit.MillimeterOfMercury: return _value/7.50061561302643e-3; + case PressureUnit.NewtonPerSquareCentimeter: return _value*1e4; + case PressureUnit.NewtonPerSquareMeter: return _value; + case PressureUnit.NewtonPerSquareMillimeter: return _value*1e6; + case PressureUnit.Pascal: return _value; + case PressureUnit.PoundForcePerSquareFoot: return _value*47.8802631216372; + case PressureUnit.PoundForcePerSquareInch: return _value*6894.75729316836; + case PressureUnit.Psi: return _value*6.89464975179*1e3; + case PressureUnit.TechnicalAtmosphere: return _value*9.80680592331*1e4; + case PressureUnit.TonneForcePerSquareCentimeter: return _value*98066501.9960652; + case PressureUnit.TonneForcePerSquareMeter: return _value*9806.65019960653; + case PressureUnit.TonneForcePerSquareMillimeter: return _value*9806650199.60653; + case PressureUnit.Torr: return _value*1.3332266752*1e2; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(PressureUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs index 37ac9dd93a..0bbb6ba290 100644 --- a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct PressureChangeRate : IComparable, IComparable - /// Base unit of PressureChangeRate. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _pascalsPerSecond; + private readonly PressureChangeRateUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public PressureChangeRate() : this(0) + public PressureChangeRate() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public PressureChangeRate(double pascalspersecond) { - _pascalsPerSecond = Convert.ToDouble(pascalspersecond); + _value = Convert.ToDouble(pascalspersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + PressureChangeRate(double numericValue, PressureChangeRateUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit PascalPerSecond. + /// + /// Value assuming base unit PascalPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - PressureChangeRate(long pascalspersecond) - { - _pascalsPerSecond = Convert.ToDouble(pascalspersecond); - } + PressureChangeRate(long pascalspersecond) : this(Convert.ToDouble(pascalspersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit PascalPerSecond. + /// + /// Value assuming base unit PascalPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - PressureChangeRate(decimal pascalspersecond) - { - _pascalsPerSecond = Convert.ToDouble(pascalspersecond); - } + PressureChangeRate(decimal pascalspersecond) : this(Convert.ToDouble(pascalspersecond), BaseUnit) { } #region Properties @@ -119,56 +156,34 @@ public PressureChangeRate(double pascalspersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static PressureChangeRateUnit BaseUnit - { - get { return PressureChangeRateUnit.PascalPerSecond; } - } + public static PressureChangeRateUnit BaseUnit => PressureChangeRateUnit.PascalPerSecond; /// /// All units of measurement for the PressureChangeRate quantity. /// public static PressureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().ToArray(); - /// /// Get PressureChangeRate in AtmospheresPerSecond. /// - public double AtmospheresPerSecond - { - get { return _pascalsPerSecond / (1.01325*1e5); } - } - + public double AtmospheresPerSecond => As(PressureChangeRateUnit.AtmospherePerSecond); /// /// Get PressureChangeRate in KilopascalsPerSecond. /// - public double KilopascalsPerSecond - { - get { return (_pascalsPerSecond) / 1e3d; } - } - + public double KilopascalsPerSecond => As(PressureChangeRateUnit.KilopascalPerSecond); /// /// Get PressureChangeRate in MegapascalsPerSecond. /// - public double MegapascalsPerSecond - { - get { return (_pascalsPerSecond) / 1e6d; } - } - + public double MegapascalsPerSecond => As(PressureChangeRateUnit.MegapascalPerSecond); /// /// Get PressureChangeRate in PascalsPerSecond. /// - public double PascalsPerSecond - { - get { return _pascalsPerSecond; } - } + public double PascalsPerSecond => As(PressureChangeRateUnit.PascalPerSecond); #endregion #region Static - public static PressureChangeRate Zero - { - get { return new PressureChangeRate(); } - } + public static PressureChangeRate Zero => new PressureChangeRate(0, BaseUnit); /// /// Get PressureChangeRate from AtmospheresPerSecond. @@ -176,17 +191,13 @@ public static PressureChangeRate Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static PressureChangeRate FromAtmospheresPerSecond(double atmospherespersecond) - { - double value = (double) atmospherespersecond; - return new PressureChangeRate(value * 1.01325*1e5); - } #else public static PressureChangeRate FromAtmospheresPerSecond(QuantityValue atmospherespersecond) +#endif { double value = (double) atmospherespersecond; - return new PressureChangeRate((value * 1.01325*1e5)); + return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); } -#endif /// /// Get PressureChangeRate from KilopascalsPerSecond. @@ -194,17 +205,13 @@ public static PressureChangeRate FromAtmospheresPerSecond(QuantityValue atmosphe #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static PressureChangeRate FromKilopascalsPerSecond(double kilopascalspersecond) - { - double value = (double) kilopascalspersecond; - return new PressureChangeRate((value) * 1e3d); - } #else public static PressureChangeRate FromKilopascalsPerSecond(QuantityValue kilopascalspersecond) +#endif { double value = (double) kilopascalspersecond; - return new PressureChangeRate(((value) * 1e3d)); + return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); } -#endif /// /// Get PressureChangeRate from MegapascalsPerSecond. @@ -212,17 +219,13 @@ public static PressureChangeRate FromKilopascalsPerSecond(QuantityValue kilopasc #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static PressureChangeRate FromMegapascalsPerSecond(double megapascalspersecond) - { - double value = (double) megapascalspersecond; - return new PressureChangeRate((value) * 1e6d); - } #else public static PressureChangeRate FromMegapascalsPerSecond(QuantityValue megapascalspersecond) +#endif { double value = (double) megapascalspersecond; - return new PressureChangeRate(((value) * 1e6d)); + return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); } -#endif /// /// Get PressureChangeRate from PascalsPerSecond. @@ -230,17 +233,13 @@ public static PressureChangeRate FromMegapascalsPerSecond(QuantityValue megapasc #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static PressureChangeRate FromPascalsPerSecond(double pascalspersecond) - { - double value = (double) pascalspersecond; - return new PressureChangeRate(value); - } #else public static PressureChangeRate FromPascalsPerSecond(QuantityValue pascalspersecond) +#endif { double value = (double) pascalspersecond; - return new PressureChangeRate((value)); + return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerSecond); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -320,20 +319,7 @@ public static PressureChangeRate From(double value, PressureChangeRateUnit fromU public static PressureChangeRate From(QuantityValue value, PressureChangeRateUnit fromUnit) #endif { - switch (fromUnit) - { - case PressureChangeRateUnit.AtmospherePerSecond: - return FromAtmospheresPerSecond(value); - case PressureChangeRateUnit.KilopascalPerSecond: - return FromKilopascalsPerSecond(value); - case PressureChangeRateUnit.MegapascalPerSecond: - return FromMegapascalsPerSecond(value); - case PressureChangeRateUnit.PascalPerSecond: - return FromPascalsPerSecond(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new PressureChangeRate((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -350,20 +336,8 @@ public static PressureChangeRate From(QuantityValue value, PressureChangeRateUni { return null; } - switch (fromUnit) - { - case PressureChangeRateUnit.AtmospherePerSecond: - return FromAtmospheresPerSecond(value.Value); - case PressureChangeRateUnit.KilopascalPerSecond: - return FromKilopascalsPerSecond(value.Value); - case PressureChangeRateUnit.MegapascalPerSecond: - return FromMegapascalsPerSecond(value.Value); - case PressureChangeRateUnit.PascalPerSecond: - return FromPascalsPerSecond(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new PressureChangeRate((double)value.Value, fromUnit); } #endif @@ -382,12 +356,29 @@ public static string GetAbbreviation(PressureChangeRateUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(PressureChangeRateUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + PressureChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -398,37 +389,37 @@ public static string GetAbbreviation(PressureChangeRateUnit unit, [CanBeNull] Cu #if !WINDOWS_UWP public static PressureChangeRate operator -(PressureChangeRate right) { - return new PressureChangeRate(-right._pascalsPerSecond); + return new PressureChangeRate(-right.Value, right.Unit); } public static PressureChangeRate operator +(PressureChangeRate left, PressureChangeRate right) { - return new PressureChangeRate(left._pascalsPerSecond + right._pascalsPerSecond); + return new PressureChangeRate(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static PressureChangeRate operator -(PressureChangeRate left, PressureChangeRate right) { - return new PressureChangeRate(left._pascalsPerSecond - right._pascalsPerSecond); + return new PressureChangeRate(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static PressureChangeRate operator *(double left, PressureChangeRate right) { - return new PressureChangeRate(left*right._pascalsPerSecond); + return new PressureChangeRate(left * right.Value, right.Unit); } public static PressureChangeRate operator *(PressureChangeRate left, double right) { - return new PressureChangeRate(left._pascalsPerSecond*(double)right); + return new PressureChangeRate(left.Value * right, left.Unit); } public static PressureChangeRate operator /(PressureChangeRate left, double right) { - return new PressureChangeRate(left._pascalsPerSecond/(double)right); + return new PressureChangeRate(left.Value / right, left.Unit); } public static double operator /(PressureChangeRate left, PressureChangeRate right) { - return Convert.ToDouble(left._pascalsPerSecond/right._pascalsPerSecond); + return left.PascalsPerSecond / right.PascalsPerSecond; } #endif @@ -451,43 +442,43 @@ public int CompareTo(object obj) #endif int CompareTo(PressureChangeRate other) { - return _pascalsPerSecond.CompareTo(other._pascalsPerSecond); + return AsBaseUnitPascalsPerSecond().CompareTo(other.AsBaseUnitPascalsPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(PressureChangeRate left, PressureChangeRate right) { - return left._pascalsPerSecond <= right._pascalsPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(PressureChangeRate left, PressureChangeRate right) { - return left._pascalsPerSecond >= right._pascalsPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(PressureChangeRate left, PressureChangeRate right) { - return left._pascalsPerSecond < right._pascalsPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(PressureChangeRate left, PressureChangeRate right) { - return left._pascalsPerSecond > right._pascalsPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(PressureChangeRate left, PressureChangeRate right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._pascalsPerSecond == right._pascalsPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(PressureChangeRate left, PressureChangeRate right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._pascalsPerSecond != right._pascalsPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -499,7 +490,7 @@ public override bool Equals(object obj) return false; } - return _pascalsPerSecond.Equals(((PressureChangeRate) obj)._pascalsPerSecond); + return AsBaseUnitPascalsPerSecond().Equals(((PressureChangeRate) obj).AsBaseUnitPascalsPerSecond()); } /// @@ -512,12 +503,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(PressureChangeRate other, PressureChangeRate maxError) { - return Math.Abs(_pascalsPerSecond - other._pascalsPerSecond) <= maxError._pascalsPerSecond; + return Math.Abs(AsBaseUnitPascalsPerSecond() - other.AsBaseUnitPascalsPerSecond()) <= maxError.AsBaseUnitPascalsPerSecond(); } public override int GetHashCode() { - return _pascalsPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -527,20 +518,22 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(PressureChangeRateUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitPascalsPerSecond(); + switch (unit) { - case PressureChangeRateUnit.AtmospherePerSecond: - return AtmospheresPerSecond; - case PressureChangeRateUnit.KilopascalPerSecond: - return KilopascalsPerSecond; - case PressureChangeRateUnit.MegapascalPerSecond: - return MegapascalsPerSecond; - case PressureChangeRateUnit.PascalPerSecond: - return PascalsPerSecond; + case PressureChangeRateUnit.AtmospherePerSecond: return baseUnitValue / (1.01325*1e5); + case PressureChangeRateUnit.KilopascalPerSecond: return (baseUnitValue) / 1e3d; + case PressureChangeRateUnit.MegapascalPerSecond: return (baseUnitValue) / 1e6d; + case PressureChangeRateUnit.PascalPerSecond: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -582,7 +575,11 @@ public static PressureChangeRate Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -601,17 +598,24 @@ public static PressureChangeRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static PressureChangeRate Parse(string str, [CanBeNull] Culture culture) + public static PressureChangeRate Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -637,16 +641,41 @@ public static bool TryParse([CanBeNull] string str, out PressureChangeRate resul /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out PressureChangeRate result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out PressureChangeRate result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -659,6 +688,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -672,11 +702,14 @@ public static PressureChangeRateUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static PressureChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -685,6 +718,8 @@ public static PressureChangeRateUnit ParseUnit(string str, [CanBeNull] string cu /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -697,18 +732,18 @@ public static PressureChangeRateUnit ParseUnit(string str, [CanBeNull] string cu #else public #endif - static PressureChangeRateUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static PressureChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == PressureChangeRateUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized PressureChangeRateUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -717,6 +752,7 @@ static PressureChangeRateUnit ParseUnit(string str, IFormatProvider formatProvid #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is PascalPerSecond /// @@ -728,7 +764,7 @@ static PressureChangeRateUnit ParseUnit(string str, IFormatProvider formatProvid /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -745,74 +781,132 @@ public string ToString(PressureChangeRateUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(PressureChangeRateUnit unit, [CanBeNull] Culture culture) + public string ToString( + PressureChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(PressureChangeRateUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + PressureChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(PressureChangeRateUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + PressureChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of PressureChangeRate /// - public static PressureChangeRate MaxValue - { - get - { - return new PressureChangeRate(double.MaxValue); - } - } + public static PressureChangeRate MaxValue => new PressureChangeRate(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of PressureChangeRate /// - public static PressureChangeRate MinValue + public static PressureChangeRate MinValue => new PressureChangeRate(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitPascalsPerSecond() { - get + if (Unit == PressureChangeRateUnit.PascalPerSecond) { return _value; } + + switch (Unit) { - return new PressureChangeRate(double.MinValue); - } - } - } + case PressureChangeRateUnit.AtmospherePerSecond: return _value * 1.01325*1e5; + case PressureChangeRateUnit.KilopascalPerSecond: return (_value) * 1e3d; + case PressureChangeRateUnit.MegapascalPerSecond: return (_value) * 1e6d; + case PressureChangeRateUnit.PascalPerSecond: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(PressureChangeRateUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs index a91bd5b313..85f2b5431a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Ratio : IComparable, IComparable #endif { /// - /// Base unit of Ratio. + /// The numeric value this quantity was constructed with. /// - private readonly double _decimalFractions; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RatioUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Ratio() : this(0) + public Ratio() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Ratio(double decimalfractions) { - _decimalFractions = Convert.ToDouble(decimalfractions); + _value = Convert.ToDouble(decimalfractions); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Ratio(double numericValue, RatioUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit DecimalFraction. + /// + /// Value assuming base unit DecimalFraction. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Ratio(long decimalfractions) - { - _decimalFractions = Convert.ToDouble(decimalfractions); - } + Ratio(long decimalfractions) : this(Convert.ToDouble(decimalfractions), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit DecimalFraction. + /// + /// Value assuming base unit DecimalFraction. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Ratio(decimal decimalfractions) - { - _decimalFractions = Convert.ToDouble(decimalfractions); - } + Ratio(decimal decimalfractions) : this(Convert.ToDouble(decimalfractions), BaseUnit) { } #region Properties @@ -119,72 +156,42 @@ public Ratio(double decimalfractions) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static RatioUnit BaseUnit - { - get { return RatioUnit.DecimalFraction; } - } + public static RatioUnit BaseUnit => RatioUnit.DecimalFraction; /// /// All units of measurement for the Ratio quantity. /// public static RatioUnit[] Units { get; } = Enum.GetValues(typeof(RatioUnit)).Cast().ToArray(); - /// /// Get Ratio in DecimalFractions. /// - public double DecimalFractions - { - get { return _decimalFractions; } - } - + public double DecimalFractions => As(RatioUnit.DecimalFraction); /// /// Get Ratio in PartsPerBillion. /// - public double PartsPerBillion - { - get { return _decimalFractions*1e9; } - } - + public double PartsPerBillion => As(RatioUnit.PartPerBillion); /// /// Get Ratio in PartsPerMillion. /// - public double PartsPerMillion - { - get { return _decimalFractions*1e6; } - } - + public double PartsPerMillion => As(RatioUnit.PartPerMillion); /// /// Get Ratio in PartsPerThousand. /// - public double PartsPerThousand - { - get { return _decimalFractions*1e3; } - } - + public double PartsPerThousand => As(RatioUnit.PartPerThousand); /// /// Get Ratio in PartsPerTrillion. /// - public double PartsPerTrillion - { - get { return _decimalFractions*1e12; } - } - + public double PartsPerTrillion => As(RatioUnit.PartPerTrillion); /// /// Get Ratio in Percent. /// - public double Percent - { - get { return _decimalFractions*1e2; } - } + public double Percent => As(RatioUnit.Percent); #endregion #region Static - public static Ratio Zero - { - get { return new Ratio(); } - } + public static Ratio Zero => new Ratio(0, BaseUnit); /// /// Get Ratio from DecimalFractions. @@ -192,17 +199,13 @@ public static Ratio Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Ratio FromDecimalFractions(double decimalfractions) - { - double value = (double) decimalfractions; - return new Ratio(value); - } #else public static Ratio FromDecimalFractions(QuantityValue decimalfractions) +#endif { double value = (double) decimalfractions; - return new Ratio((value)); + return new Ratio(value, RatioUnit.DecimalFraction); } -#endif /// /// Get Ratio from PartsPerBillion. @@ -210,17 +213,13 @@ public static Ratio FromDecimalFractions(QuantityValue decimalfractions) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Ratio FromPartsPerBillion(double partsperbillion) - { - double value = (double) partsperbillion; - return new Ratio(value/1e9); - } #else public static Ratio FromPartsPerBillion(QuantityValue partsperbillion) +#endif { double value = (double) partsperbillion; - return new Ratio((value/1e9)); + return new Ratio(value, RatioUnit.PartPerBillion); } -#endif /// /// Get Ratio from PartsPerMillion. @@ -228,17 +227,13 @@ public static Ratio FromPartsPerBillion(QuantityValue partsperbillion) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Ratio FromPartsPerMillion(double partspermillion) - { - double value = (double) partspermillion; - return new Ratio(value/1e6); - } #else public static Ratio FromPartsPerMillion(QuantityValue partspermillion) +#endif { double value = (double) partspermillion; - return new Ratio((value/1e6)); + return new Ratio(value, RatioUnit.PartPerMillion); } -#endif /// /// Get Ratio from PartsPerThousand. @@ -246,17 +241,13 @@ public static Ratio FromPartsPerMillion(QuantityValue partspermillion) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Ratio FromPartsPerThousand(double partsperthousand) - { - double value = (double) partsperthousand; - return new Ratio(value/1e3); - } #else public static Ratio FromPartsPerThousand(QuantityValue partsperthousand) +#endif { double value = (double) partsperthousand; - return new Ratio((value/1e3)); + return new Ratio(value, RatioUnit.PartPerThousand); } -#endif /// /// Get Ratio from PartsPerTrillion. @@ -264,17 +255,13 @@ public static Ratio FromPartsPerThousand(QuantityValue partsperthousand) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Ratio FromPartsPerTrillion(double partspertrillion) - { - double value = (double) partspertrillion; - return new Ratio(value/1e12); - } #else public static Ratio FromPartsPerTrillion(QuantityValue partspertrillion) +#endif { double value = (double) partspertrillion; - return new Ratio((value/1e12)); + return new Ratio(value, RatioUnit.PartPerTrillion); } -#endif /// /// Get Ratio from Percent. @@ -282,17 +269,13 @@ public static Ratio FromPartsPerTrillion(QuantityValue partspertrillion) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Ratio FromPercent(double percent) - { - double value = (double) percent; - return new Ratio(value/1e2); - } #else public static Ratio FromPercent(QuantityValue percent) +#endif { double value = (double) percent; - return new Ratio((value/1e2)); + return new Ratio(value, RatioUnit.Percent); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -402,24 +385,7 @@ public static Ratio From(double value, RatioUnit fromUnit) public static Ratio From(QuantityValue value, RatioUnit fromUnit) #endif { - switch (fromUnit) - { - case RatioUnit.DecimalFraction: - return FromDecimalFractions(value); - case RatioUnit.PartPerBillion: - return FromPartsPerBillion(value); - case RatioUnit.PartPerMillion: - return FromPartsPerMillion(value); - case RatioUnit.PartPerThousand: - return FromPartsPerThousand(value); - case RatioUnit.PartPerTrillion: - return FromPartsPerTrillion(value); - case RatioUnit.Percent: - return FromPercent(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Ratio((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -436,24 +402,8 @@ public static Ratio From(QuantityValue value, RatioUnit fromUnit) { return null; } - switch (fromUnit) - { - case RatioUnit.DecimalFraction: - return FromDecimalFractions(value.Value); - case RatioUnit.PartPerBillion: - return FromPartsPerBillion(value.Value); - case RatioUnit.PartPerMillion: - return FromPartsPerMillion(value.Value); - case RatioUnit.PartPerThousand: - return FromPartsPerThousand(value.Value); - case RatioUnit.PartPerTrillion: - return FromPartsPerTrillion(value.Value); - case RatioUnit.Percent: - return FromPercent(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Ratio((double)value.Value, fromUnit); } #endif @@ -472,12 +422,29 @@ public static string GetAbbreviation(RatioUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(RatioUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + RatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -488,37 +455,37 @@ public static string GetAbbreviation(RatioUnit unit, [CanBeNull] Culture culture #if !WINDOWS_UWP public static Ratio operator -(Ratio right) { - return new Ratio(-right._decimalFractions); + return new Ratio(-right.Value, right.Unit); } public static Ratio operator +(Ratio left, Ratio right) { - return new Ratio(left._decimalFractions + right._decimalFractions); + return new Ratio(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Ratio operator -(Ratio left, Ratio right) { - return new Ratio(left._decimalFractions - right._decimalFractions); + return new Ratio(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Ratio operator *(double left, Ratio right) { - return new Ratio(left*right._decimalFractions); + return new Ratio(left * right.Value, right.Unit); } public static Ratio operator *(Ratio left, double right) { - return new Ratio(left._decimalFractions*(double)right); + return new Ratio(left.Value * right, left.Unit); } public static Ratio operator /(Ratio left, double right) { - return new Ratio(left._decimalFractions/(double)right); + return new Ratio(left.Value / right, left.Unit); } public static double operator /(Ratio left, Ratio right) { - return Convert.ToDouble(left._decimalFractions/right._decimalFractions); + return left.DecimalFractions / right.DecimalFractions; } #endif @@ -541,43 +508,43 @@ public int CompareTo(object obj) #endif int CompareTo(Ratio other) { - return _decimalFractions.CompareTo(other._decimalFractions); + return AsBaseUnitDecimalFractions().CompareTo(other.AsBaseUnitDecimalFractions()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Ratio left, Ratio right) { - return left._decimalFractions <= right._decimalFractions; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Ratio left, Ratio right) { - return left._decimalFractions >= right._decimalFractions; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Ratio left, Ratio right) { - return left._decimalFractions < right._decimalFractions; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Ratio left, Ratio right) { - return left._decimalFractions > right._decimalFractions; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Ratio left, Ratio right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._decimalFractions == right._decimalFractions; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Ratio left, Ratio right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._decimalFractions != right._decimalFractions; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -589,7 +556,7 @@ public override bool Equals(object obj) return false; } - return _decimalFractions.Equals(((Ratio) obj)._decimalFractions); + return AsBaseUnitDecimalFractions().Equals(((Ratio) obj).AsBaseUnitDecimalFractions()); } /// @@ -602,12 +569,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Ratio other, Ratio maxError) { - return Math.Abs(_decimalFractions - other._decimalFractions) <= maxError._decimalFractions; + return Math.Abs(AsBaseUnitDecimalFractions() - other.AsBaseUnitDecimalFractions()) <= maxError.AsBaseUnitDecimalFractions(); } public override int GetHashCode() { - return _decimalFractions.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -617,24 +584,24 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(RatioUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitDecimalFractions(); + switch (unit) { - case RatioUnit.DecimalFraction: - return DecimalFractions; - case RatioUnit.PartPerBillion: - return PartsPerBillion; - case RatioUnit.PartPerMillion: - return PartsPerMillion; - case RatioUnit.PartPerThousand: - return PartsPerThousand; - case RatioUnit.PartPerTrillion: - return PartsPerTrillion; - case RatioUnit.Percent: - return Percent; + case RatioUnit.DecimalFraction: return baseUnitValue; + case RatioUnit.PartPerBillion: return baseUnitValue*1e9; + case RatioUnit.PartPerMillion: return baseUnitValue*1e6; + case RatioUnit.PartPerThousand: return baseUnitValue*1e3; + case RatioUnit.PartPerTrillion: return baseUnitValue*1e12; + case RatioUnit.Percent: return baseUnitValue*1e2; default: throw new NotImplementedException("unit: " + unit); @@ -676,7 +643,11 @@ public static Ratio Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -695,17 +666,24 @@ public static Ratio Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Ratio Parse(string str, [CanBeNull] Culture culture) + public static Ratio Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -731,16 +709,41 @@ public static bool TryParse([CanBeNull] string str, out Ratio result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Ratio result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Ratio result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -753,6 +756,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -766,11 +770,14 @@ public static RatioUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static RatioUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -779,6 +786,8 @@ public static RatioUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -791,18 +800,18 @@ public static RatioUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static RatioUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static RatioUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == RatioUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RatioUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -811,6 +820,7 @@ static RatioUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is DecimalFraction /// @@ -822,7 +832,7 @@ static RatioUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -839,74 +849,134 @@ public string ToString(RatioUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(RatioUnit unit, [CanBeNull] Culture culture) + public string ToString( + RatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(RatioUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + RatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(RatioUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + RatioUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Ratio /// - public static Ratio MaxValue - { - get - { - return new Ratio(double.MaxValue); - } - } + public static Ratio MaxValue => new Ratio(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Ratio /// - public static Ratio MinValue + public static Ratio MinValue => new Ratio(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitDecimalFractions() { - get + if (Unit == RatioUnit.DecimalFraction) { return _value; } + + switch (Unit) { - return new Ratio(double.MinValue); - } - } - } + case RatioUnit.DecimalFraction: return _value; + case RatioUnit.PartPerBillion: return _value/1e9; + case RatioUnit.PartPerMillion: return _value/1e6; + case RatioUnit.PartPerThousand: return _value/1e3; + case RatioUnit.PartPerTrillion: return _value/1e12; + case RatioUnit.Percent: return _value/1e2; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(RatioUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs index c2c9020780..ba9259d3e7 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ReactiveEnergy : IComparable, IComparable #endif { /// - /// Base unit of ReactiveEnergy. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ReactiveEnergyUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _voltampereReactiveHours; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ReactiveEnergy() : this(0) + public ReactiveEnergy() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ReactiveEnergy(double voltamperereactivehours) { - _voltampereReactiveHours = Convert.ToDouble(voltamperereactivehours); + _value = Convert.ToDouble(voltamperereactivehours); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ReactiveEnergy(double numericValue, ReactiveEnergyUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit VoltampereReactiveHour. + /// + /// Value assuming base unit VoltampereReactiveHour. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ReactiveEnergy(long voltamperereactivehours) - { - _voltampereReactiveHours = Convert.ToDouble(voltamperereactivehours); - } + ReactiveEnergy(long voltamperereactivehours) : this(Convert.ToDouble(voltamperereactivehours), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit VoltampereReactiveHour. + /// + /// Value assuming base unit VoltampereReactiveHour. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ReactiveEnergy(decimal voltamperereactivehours) - { - _voltampereReactiveHours = Convert.ToDouble(voltamperereactivehours); - } + ReactiveEnergy(decimal voltamperereactivehours) : this(Convert.ToDouble(voltamperereactivehours), BaseUnit) { } #region Properties @@ -119,48 +156,30 @@ public ReactiveEnergy(double voltamperereactivehours) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ReactiveEnergyUnit BaseUnit - { - get { return ReactiveEnergyUnit.VoltampereReactiveHour; } - } + public static ReactiveEnergyUnit BaseUnit => ReactiveEnergyUnit.VoltampereReactiveHour; /// /// All units of measurement for the ReactiveEnergy quantity. /// public static ReactiveEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast().ToArray(); - /// /// Get ReactiveEnergy in KilovoltampereReactiveHours. /// - public double KilovoltampereReactiveHours - { - get { return (_voltampereReactiveHours) / 1e3d; } - } - + public double KilovoltampereReactiveHours => As(ReactiveEnergyUnit.KilovoltampereReactiveHour); /// /// Get ReactiveEnergy in MegavoltampereReactiveHours. /// - public double MegavoltampereReactiveHours - { - get { return (_voltampereReactiveHours) / 1e6d; } - } - + public double MegavoltampereReactiveHours => As(ReactiveEnergyUnit.MegavoltampereReactiveHour); /// /// Get ReactiveEnergy in VoltampereReactiveHours. /// - public double VoltampereReactiveHours - { - get { return _voltampereReactiveHours; } - } + public double VoltampereReactiveHours => As(ReactiveEnergyUnit.VoltampereReactiveHour); #endregion #region Static - public static ReactiveEnergy Zero - { - get { return new ReactiveEnergy(); } - } + public static ReactiveEnergy Zero => new ReactiveEnergy(0, BaseUnit); /// /// Get ReactiveEnergy from KilovoltampereReactiveHours. @@ -168,17 +187,13 @@ public static ReactiveEnergy Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ReactiveEnergy FromKilovoltampereReactiveHours(double kilovoltamperereactivehours) - { - double value = (double) kilovoltamperereactivehours; - return new ReactiveEnergy((value) * 1e3d); - } #else public static ReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue kilovoltamperereactivehours) +#endif { double value = (double) kilovoltamperereactivehours; - return new ReactiveEnergy(((value) * 1e3d)); + return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); } -#endif /// /// Get ReactiveEnergy from MegavoltampereReactiveHours. @@ -186,17 +201,13 @@ public static ReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue kilov #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ReactiveEnergy FromMegavoltampereReactiveHours(double megavoltamperereactivehours) - { - double value = (double) megavoltamperereactivehours; - return new ReactiveEnergy((value) * 1e6d); - } #else public static ReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue megavoltamperereactivehours) +#endif { double value = (double) megavoltamperereactivehours; - return new ReactiveEnergy(((value) * 1e6d)); + return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); } -#endif /// /// Get ReactiveEnergy from VoltampereReactiveHours. @@ -204,17 +215,13 @@ public static ReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue megav #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ReactiveEnergy FromVoltampereReactiveHours(double voltamperereactivehours) - { - double value = (double) voltamperereactivehours; - return new ReactiveEnergy(value); - } #else public static ReactiveEnergy FromVoltampereReactiveHours(QuantityValue voltamperereactivehours) +#endif { double value = (double) voltamperereactivehours; - return new ReactiveEnergy((value)); + return new ReactiveEnergy(value, ReactiveEnergyUnit.VoltampereReactiveHour); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -279,18 +286,7 @@ public static ReactiveEnergy From(double value, ReactiveEnergyUnit fromUnit) public static ReactiveEnergy From(QuantityValue value, ReactiveEnergyUnit fromUnit) #endif { - switch (fromUnit) - { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: - return FromKilovoltampereReactiveHours(value); - case ReactiveEnergyUnit.MegavoltampereReactiveHour: - return FromMegavoltampereReactiveHours(value); - case ReactiveEnergyUnit.VoltampereReactiveHour: - return FromVoltampereReactiveHours(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ReactiveEnergy((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -307,18 +303,8 @@ public static ReactiveEnergy From(QuantityValue value, ReactiveEnergyUnit fromUn { return null; } - switch (fromUnit) - { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: - return FromKilovoltampereReactiveHours(value.Value); - case ReactiveEnergyUnit.MegavoltampereReactiveHour: - return FromMegavoltampereReactiveHours(value.Value); - case ReactiveEnergyUnit.VoltampereReactiveHour: - return FromVoltampereReactiveHours(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ReactiveEnergy((double)value.Value, fromUnit); } #endif @@ -337,12 +323,29 @@ public static string GetAbbreviation(ReactiveEnergyUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ReactiveEnergyUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ReactiveEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -353,37 +356,37 @@ public static string GetAbbreviation(ReactiveEnergyUnit unit, [CanBeNull] Cultur #if !WINDOWS_UWP public static ReactiveEnergy operator -(ReactiveEnergy right) { - return new ReactiveEnergy(-right._voltampereReactiveHours); + return new ReactiveEnergy(-right.Value, right.Unit); } public static ReactiveEnergy operator +(ReactiveEnergy left, ReactiveEnergy right) { - return new ReactiveEnergy(left._voltampereReactiveHours + right._voltampereReactiveHours); + return new ReactiveEnergy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ReactiveEnergy operator -(ReactiveEnergy left, ReactiveEnergy right) { - return new ReactiveEnergy(left._voltampereReactiveHours - right._voltampereReactiveHours); + return new ReactiveEnergy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ReactiveEnergy operator *(double left, ReactiveEnergy right) { - return new ReactiveEnergy(left*right._voltampereReactiveHours); + return new ReactiveEnergy(left * right.Value, right.Unit); } public static ReactiveEnergy operator *(ReactiveEnergy left, double right) { - return new ReactiveEnergy(left._voltampereReactiveHours*(double)right); + return new ReactiveEnergy(left.Value * right, left.Unit); } public static ReactiveEnergy operator /(ReactiveEnergy left, double right) { - return new ReactiveEnergy(left._voltampereReactiveHours/(double)right); + return new ReactiveEnergy(left.Value / right, left.Unit); } public static double operator /(ReactiveEnergy left, ReactiveEnergy right) { - return Convert.ToDouble(left._voltampereReactiveHours/right._voltampereReactiveHours); + return left.VoltampereReactiveHours / right.VoltampereReactiveHours; } #endif @@ -406,43 +409,43 @@ public int CompareTo(object obj) #endif int CompareTo(ReactiveEnergy other) { - return _voltampereReactiveHours.CompareTo(other._voltampereReactiveHours); + return AsBaseUnitVoltampereReactiveHours().CompareTo(other.AsBaseUnitVoltampereReactiveHours()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ReactiveEnergy left, ReactiveEnergy right) { - return left._voltampereReactiveHours <= right._voltampereReactiveHours; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ReactiveEnergy left, ReactiveEnergy right) { - return left._voltampereReactiveHours >= right._voltampereReactiveHours; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ReactiveEnergy left, ReactiveEnergy right) { - return left._voltampereReactiveHours < right._voltampereReactiveHours; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ReactiveEnergy left, ReactiveEnergy right) { - return left._voltampereReactiveHours > right._voltampereReactiveHours; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ReactiveEnergy left, ReactiveEnergy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltampereReactiveHours == right._voltampereReactiveHours; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ReactiveEnergy left, ReactiveEnergy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltampereReactiveHours != right._voltampereReactiveHours; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -454,7 +457,7 @@ public override bool Equals(object obj) return false; } - return _voltampereReactiveHours.Equals(((ReactiveEnergy) obj)._voltampereReactiveHours); + return AsBaseUnitVoltampereReactiveHours().Equals(((ReactiveEnergy) obj).AsBaseUnitVoltampereReactiveHours()); } /// @@ -467,12 +470,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ReactiveEnergy other, ReactiveEnergy maxError) { - return Math.Abs(_voltampereReactiveHours - other._voltampereReactiveHours) <= maxError._voltampereReactiveHours; + return Math.Abs(AsBaseUnitVoltampereReactiveHours() - other.AsBaseUnitVoltampereReactiveHours()) <= maxError.AsBaseUnitVoltampereReactiveHours(); } public override int GetHashCode() { - return _voltampereReactiveHours.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -482,18 +485,21 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ReactiveEnergyUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitVoltampereReactiveHours(); + switch (unit) { - case ReactiveEnergyUnit.KilovoltampereReactiveHour: - return KilovoltampereReactiveHours; - case ReactiveEnergyUnit.MegavoltampereReactiveHour: - return MegavoltampereReactiveHours; - case ReactiveEnergyUnit.VoltampereReactiveHour: - return VoltampereReactiveHours; + case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (baseUnitValue) / 1e3d; + case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (baseUnitValue) / 1e6d; + case ReactiveEnergyUnit.VoltampereReactiveHour: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -535,7 +541,11 @@ public static ReactiveEnergy Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -554,17 +564,24 @@ public static ReactiveEnergy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ReactiveEnergy Parse(string str, [CanBeNull] Culture culture) + public static ReactiveEnergy Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -590,16 +607,41 @@ public static bool TryParse([CanBeNull] string str, out ReactiveEnergy result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ReactiveEnergy result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ReactiveEnergy result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -612,6 +654,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -625,11 +668,14 @@ public static ReactiveEnergyUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ReactiveEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -638,6 +684,8 @@ public static ReactiveEnergyUnit ParseUnit(string str, [CanBeNull] string cultur /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -650,18 +698,18 @@ public static ReactiveEnergyUnit ParseUnit(string str, [CanBeNull] string cultur #else public #endif - static ReactiveEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ReactiveEnergyUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ReactiveEnergyUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ReactiveEnergyUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -670,6 +718,7 @@ static ReactiveEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is VoltampereReactiveHour /// @@ -681,7 +730,7 @@ static ReactiveEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -698,74 +747,131 @@ public string ToString(ReactiveEnergyUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ReactiveEnergyUnit unit, [CanBeNull] Culture culture) + public string ToString( + ReactiveEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ReactiveEnergyUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ReactiveEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ReactiveEnergyUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ReactiveEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ReactiveEnergy /// - public static ReactiveEnergy MaxValue - { - get - { - return new ReactiveEnergy(double.MaxValue); - } - } + public static ReactiveEnergy MaxValue => new ReactiveEnergy(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ReactiveEnergy /// - public static ReactiveEnergy MinValue + public static ReactiveEnergy MinValue => new ReactiveEnergy(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitVoltampereReactiveHours() { - get + if (Unit == ReactiveEnergyUnit.VoltampereReactiveHour) { return _value; } + + switch (Unit) { - return new ReactiveEnergy(double.MinValue); - } - } - } + case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (_value) * 1e3d; + case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (_value) * 1e6d; + case ReactiveEnergyUnit.VoltampereReactiveHour: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ReactiveEnergyUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs b/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs index 4f2b1c4de1..0574c7f98c 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReactivePower.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ReactivePower : IComparable, IComparable #endif { /// - /// Base unit of ReactivePower. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _voltamperesReactive; + private readonly ReactivePowerUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ReactivePower() : this(0) + public ReactivePower() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ReactivePower(double voltamperesreactive) { - _voltamperesReactive = Convert.ToDouble(voltamperesreactive); + _value = Convert.ToDouble(voltamperesreactive); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ReactivePower(double numericValue, ReactivePowerUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit VoltampereReactive. + /// + /// Value assuming base unit VoltampereReactive. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ReactivePower(long voltamperesreactive) - { - _voltamperesReactive = Convert.ToDouble(voltamperesreactive); - } + ReactivePower(long voltamperesreactive) : this(Convert.ToDouble(voltamperesreactive), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit VoltampereReactive. + /// + /// Value assuming base unit VoltampereReactive. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ReactivePower(decimal voltamperesreactive) - { - _voltamperesReactive = Convert.ToDouble(voltamperesreactive); - } + ReactivePower(decimal voltamperesreactive) : this(Convert.ToDouble(voltamperesreactive), BaseUnit) { } #region Properties @@ -119,56 +156,34 @@ public ReactivePower(double voltamperesreactive) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ReactivePowerUnit BaseUnit - { - get { return ReactivePowerUnit.VoltampereReactive; } - } + public static ReactivePowerUnit BaseUnit => ReactivePowerUnit.VoltampereReactive; /// /// All units of measurement for the ReactivePower quantity. /// public static ReactivePowerUnit[] Units { get; } = Enum.GetValues(typeof(ReactivePowerUnit)).Cast().ToArray(); - /// /// Get ReactivePower in GigavoltamperesReactive. /// - public double GigavoltamperesReactive - { - get { return (_voltamperesReactive) / 1e9d; } - } - + public double GigavoltamperesReactive => As(ReactivePowerUnit.GigavoltampereReactive); /// /// Get ReactivePower in KilovoltamperesReactive. /// - public double KilovoltamperesReactive - { - get { return (_voltamperesReactive) / 1e3d; } - } - + public double KilovoltamperesReactive => As(ReactivePowerUnit.KilovoltampereReactive); /// /// Get ReactivePower in MegavoltamperesReactive. /// - public double MegavoltamperesReactive - { - get { return (_voltamperesReactive) / 1e6d; } - } - + public double MegavoltamperesReactive => As(ReactivePowerUnit.MegavoltampereReactive); /// /// Get ReactivePower in VoltamperesReactive. /// - public double VoltamperesReactive - { - get { return _voltamperesReactive; } - } + public double VoltamperesReactive => As(ReactivePowerUnit.VoltampereReactive); #endregion #region Static - public static ReactivePower Zero - { - get { return new ReactivePower(); } - } + public static ReactivePower Zero => new ReactivePower(0, BaseUnit); /// /// Get ReactivePower from GigavoltamperesReactive. @@ -176,17 +191,13 @@ public static ReactivePower Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ReactivePower FromGigavoltamperesReactive(double gigavoltamperesreactive) - { - double value = (double) gigavoltamperesreactive; - return new ReactivePower((value) * 1e9d); - } #else public static ReactivePower FromGigavoltamperesReactive(QuantityValue gigavoltamperesreactive) +#endif { double value = (double) gigavoltamperesreactive; - return new ReactivePower(((value) * 1e9d)); + return new ReactivePower(value, ReactivePowerUnit.GigavoltampereReactive); } -#endif /// /// Get ReactivePower from KilovoltamperesReactive. @@ -194,17 +205,13 @@ public static ReactivePower FromGigavoltamperesReactive(QuantityValue gigavoltam #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ReactivePower FromKilovoltamperesReactive(double kilovoltamperesreactive) - { - double value = (double) kilovoltamperesreactive; - return new ReactivePower((value) * 1e3d); - } #else public static ReactivePower FromKilovoltamperesReactive(QuantityValue kilovoltamperesreactive) +#endif { double value = (double) kilovoltamperesreactive; - return new ReactivePower(((value) * 1e3d)); + return new ReactivePower(value, ReactivePowerUnit.KilovoltampereReactive); } -#endif /// /// Get ReactivePower from MegavoltamperesReactive. @@ -212,17 +219,13 @@ public static ReactivePower FromKilovoltamperesReactive(QuantityValue kilovoltam #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ReactivePower FromMegavoltamperesReactive(double megavoltamperesreactive) - { - double value = (double) megavoltamperesreactive; - return new ReactivePower((value) * 1e6d); - } #else public static ReactivePower FromMegavoltamperesReactive(QuantityValue megavoltamperesreactive) +#endif { double value = (double) megavoltamperesreactive; - return new ReactivePower(((value) * 1e6d)); + return new ReactivePower(value, ReactivePowerUnit.MegavoltampereReactive); } -#endif /// /// Get ReactivePower from VoltamperesReactive. @@ -230,17 +233,13 @@ public static ReactivePower FromMegavoltamperesReactive(QuantityValue megavoltam #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ReactivePower FromVoltamperesReactive(double voltamperesreactive) - { - double value = (double) voltamperesreactive; - return new ReactivePower(value); - } #else public static ReactivePower FromVoltamperesReactive(QuantityValue voltamperesreactive) +#endif { double value = (double) voltamperesreactive; - return new ReactivePower((value)); + return new ReactivePower(value, ReactivePowerUnit.VoltampereReactive); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -320,20 +319,7 @@ public static ReactivePower From(double value, ReactivePowerUnit fromUnit) public static ReactivePower From(QuantityValue value, ReactivePowerUnit fromUnit) #endif { - switch (fromUnit) - { - case ReactivePowerUnit.GigavoltampereReactive: - return FromGigavoltamperesReactive(value); - case ReactivePowerUnit.KilovoltampereReactive: - return FromKilovoltamperesReactive(value); - case ReactivePowerUnit.MegavoltampereReactive: - return FromMegavoltamperesReactive(value); - case ReactivePowerUnit.VoltampereReactive: - return FromVoltamperesReactive(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ReactivePower((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -350,20 +336,8 @@ public static ReactivePower From(QuantityValue value, ReactivePowerUnit fromUnit { return null; } - switch (fromUnit) - { - case ReactivePowerUnit.GigavoltampereReactive: - return FromGigavoltamperesReactive(value.Value); - case ReactivePowerUnit.KilovoltampereReactive: - return FromKilovoltamperesReactive(value.Value); - case ReactivePowerUnit.MegavoltampereReactive: - return FromMegavoltamperesReactive(value.Value); - case ReactivePowerUnit.VoltampereReactive: - return FromVoltamperesReactive(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ReactivePower((double)value.Value, fromUnit); } #endif @@ -382,12 +356,29 @@ public static string GetAbbreviation(ReactivePowerUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ReactivePowerUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ReactivePowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -398,37 +389,37 @@ public static string GetAbbreviation(ReactivePowerUnit unit, [CanBeNull] Culture #if !WINDOWS_UWP public static ReactivePower operator -(ReactivePower right) { - return new ReactivePower(-right._voltamperesReactive); + return new ReactivePower(-right.Value, right.Unit); } public static ReactivePower operator +(ReactivePower left, ReactivePower right) { - return new ReactivePower(left._voltamperesReactive + right._voltamperesReactive); + return new ReactivePower(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ReactivePower operator -(ReactivePower left, ReactivePower right) { - return new ReactivePower(left._voltamperesReactive - right._voltamperesReactive); + return new ReactivePower(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ReactivePower operator *(double left, ReactivePower right) { - return new ReactivePower(left*right._voltamperesReactive); + return new ReactivePower(left * right.Value, right.Unit); } public static ReactivePower operator *(ReactivePower left, double right) { - return new ReactivePower(left._voltamperesReactive*(double)right); + return new ReactivePower(left.Value * right, left.Unit); } public static ReactivePower operator /(ReactivePower left, double right) { - return new ReactivePower(left._voltamperesReactive/(double)right); + return new ReactivePower(left.Value / right, left.Unit); } public static double operator /(ReactivePower left, ReactivePower right) { - return Convert.ToDouble(left._voltamperesReactive/right._voltamperesReactive); + return left.VoltamperesReactive / right.VoltamperesReactive; } #endif @@ -451,43 +442,43 @@ public int CompareTo(object obj) #endif int CompareTo(ReactivePower other) { - return _voltamperesReactive.CompareTo(other._voltamperesReactive); + return AsBaseUnitVoltamperesReactive().CompareTo(other.AsBaseUnitVoltamperesReactive()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ReactivePower left, ReactivePower right) { - return left._voltamperesReactive <= right._voltamperesReactive; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ReactivePower left, ReactivePower right) { - return left._voltamperesReactive >= right._voltamperesReactive; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ReactivePower left, ReactivePower right) { - return left._voltamperesReactive < right._voltamperesReactive; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ReactivePower left, ReactivePower right) { - return left._voltamperesReactive > right._voltamperesReactive; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ReactivePower left, ReactivePower right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltamperesReactive == right._voltamperesReactive; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ReactivePower left, ReactivePower right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._voltamperesReactive != right._voltamperesReactive; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -499,7 +490,7 @@ public override bool Equals(object obj) return false; } - return _voltamperesReactive.Equals(((ReactivePower) obj)._voltamperesReactive); + return AsBaseUnitVoltamperesReactive().Equals(((ReactivePower) obj).AsBaseUnitVoltamperesReactive()); } /// @@ -512,12 +503,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ReactivePower other, ReactivePower maxError) { - return Math.Abs(_voltamperesReactive - other._voltamperesReactive) <= maxError._voltamperesReactive; + return Math.Abs(AsBaseUnitVoltamperesReactive() - other.AsBaseUnitVoltamperesReactive()) <= maxError.AsBaseUnitVoltamperesReactive(); } public override int GetHashCode() { - return _voltamperesReactive.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -527,20 +518,22 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ReactivePowerUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitVoltamperesReactive(); + switch (unit) { - case ReactivePowerUnit.GigavoltampereReactive: - return GigavoltamperesReactive; - case ReactivePowerUnit.KilovoltampereReactive: - return KilovoltamperesReactive; - case ReactivePowerUnit.MegavoltampereReactive: - return MegavoltamperesReactive; - case ReactivePowerUnit.VoltampereReactive: - return VoltamperesReactive; + case ReactivePowerUnit.GigavoltampereReactive: return (baseUnitValue) / 1e9d; + case ReactivePowerUnit.KilovoltampereReactive: return (baseUnitValue) / 1e3d; + case ReactivePowerUnit.MegavoltampereReactive: return (baseUnitValue) / 1e6d; + case ReactivePowerUnit.VoltampereReactive: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -582,7 +575,11 @@ public static ReactivePower Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -601,17 +598,24 @@ public static ReactivePower Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ReactivePower Parse(string str, [CanBeNull] Culture culture) + public static ReactivePower Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -637,16 +641,41 @@ public static bool TryParse([CanBeNull] string str, out ReactivePower result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ReactivePower result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ReactivePower result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -659,6 +688,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -672,11 +702,14 @@ public static ReactivePowerUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ReactivePowerUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -685,6 +718,8 @@ public static ReactivePowerUnit ParseUnit(string str, [CanBeNull] string culture /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -697,18 +732,18 @@ public static ReactivePowerUnit ParseUnit(string str, [CanBeNull] string culture #else public #endif - static ReactivePowerUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ReactivePowerUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ReactivePowerUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ReactivePowerUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -717,6 +752,7 @@ static ReactivePowerUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is VoltampereReactive /// @@ -728,7 +764,7 @@ static ReactivePowerUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -745,74 +781,132 @@ public string ToString(ReactivePowerUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ReactivePowerUnit unit, [CanBeNull] Culture culture) + public string ToString( + ReactivePowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ReactivePowerUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ReactivePowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ReactivePowerUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ReactivePowerUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ReactivePower /// - public static ReactivePower MaxValue - { - get - { - return new ReactivePower(double.MaxValue); - } - } + public static ReactivePower MaxValue => new ReactivePower(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ReactivePower /// - public static ReactivePower MinValue + public static ReactivePower MinValue => new ReactivePower(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitVoltamperesReactive() { - get + if (Unit == ReactivePowerUnit.VoltampereReactive) { return _value; } + + switch (Unit) { - return new ReactivePower(double.MinValue); - } - } - } + case ReactivePowerUnit.GigavoltampereReactive: return (_value) * 1e9d; + case ReactivePowerUnit.KilovoltampereReactive: return (_value) * 1e3d; + case ReactivePowerUnit.MegavoltampereReactive: return (_value) * 1e6d; + case ReactivePowerUnit.VoltampereReactive: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ReactivePowerUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs index 20c0a109b9..95969a3dab 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct RotationalAcceleration : IComparable, IComparable - /// Base unit of RotationalAcceleration. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalAccelerationUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _radiansPerSecondSquared; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public RotationalAcceleration() : this(0) + public RotationalAcceleration() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public RotationalAcceleration(double radianspersecondsquared) { - _radiansPerSecondSquared = Convert.ToDouble(radianspersecondsquared); + _value = Convert.ToDouble(radianspersecondsquared); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + RotationalAcceleration(double numericValue, RotationalAccelerationUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit RadianPerSecondSquared. + /// + /// Value assuming base unit RadianPerSecondSquared. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - RotationalAcceleration(long radianspersecondsquared) - { - _radiansPerSecondSquared = Convert.ToDouble(radianspersecondsquared); - } + RotationalAcceleration(long radianspersecondsquared) : this(Convert.ToDouble(radianspersecondsquared), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit RadianPerSecondSquared. + /// + /// Value assuming base unit RadianPerSecondSquared. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - RotationalAcceleration(decimal radianspersecondsquared) - { - _radiansPerSecondSquared = Convert.ToDouble(radianspersecondsquared); - } + RotationalAcceleration(decimal radianspersecondsquared) : this(Convert.ToDouble(radianspersecondsquared), BaseUnit) { } #region Properties @@ -119,48 +156,30 @@ public RotationalAcceleration(double radianspersecondsquared) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static RotationalAccelerationUnit BaseUnit - { - get { return RotationalAccelerationUnit.RadianPerSecondSquared; } - } + public static RotationalAccelerationUnit BaseUnit => RotationalAccelerationUnit.RadianPerSecondSquared; /// /// All units of measurement for the RotationalAcceleration quantity. /// public static RotationalAccelerationUnit[] Units { get; } = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().ToArray(); - /// /// Get RotationalAcceleration in DegreesPerSecondSquared. /// - public double DegreesPerSecondSquared - { - get { return (180/Math.PI)*_radiansPerSecondSquared; } - } - + public double DegreesPerSecondSquared => As(RotationalAccelerationUnit.DegreePerSecondSquared); /// /// Get RotationalAcceleration in RadiansPerSecondSquared. /// - public double RadiansPerSecondSquared - { - get { return _radiansPerSecondSquared; } - } - + public double RadiansPerSecondSquared => As(RotationalAccelerationUnit.RadianPerSecondSquared); /// /// Get RotationalAcceleration in RevolutionsPerMinutePerSecond. /// - public double RevolutionsPerMinutePerSecond - { - get { return (60/(2*Math.PI))*_radiansPerSecondSquared; } - } + public double RevolutionsPerMinutePerSecond => As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); #endregion #region Static - public static RotationalAcceleration Zero - { - get { return new RotationalAcceleration(); } - } + public static RotationalAcceleration Zero => new RotationalAcceleration(0, BaseUnit); /// /// Get RotationalAcceleration from DegreesPerSecondSquared. @@ -168,17 +187,13 @@ public static RotationalAcceleration Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalAcceleration FromDegreesPerSecondSquared(double degreespersecondsquared) - { - double value = (double) degreespersecondsquared; - return new RotationalAcceleration((Math.PI/180)*value); - } #else public static RotationalAcceleration FromDegreesPerSecondSquared(QuantityValue degreespersecondsquared) +#endif { double value = (double) degreespersecondsquared; - return new RotationalAcceleration(((Math.PI/180)*value)); + return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); } -#endif /// /// Get RotationalAcceleration from RadiansPerSecondSquared. @@ -186,17 +201,13 @@ public static RotationalAcceleration FromDegreesPerSecondSquared(QuantityValue d #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalAcceleration FromRadiansPerSecondSquared(double radianspersecondsquared) - { - double value = (double) radianspersecondsquared; - return new RotationalAcceleration(value); - } #else public static RotationalAcceleration FromRadiansPerSecondSquared(QuantityValue radianspersecondsquared) +#endif { double value = (double) radianspersecondsquared; - return new RotationalAcceleration((value)); + return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); } -#endif /// /// Get RotationalAcceleration from RevolutionsPerMinutePerSecond. @@ -204,17 +215,13 @@ public static RotationalAcceleration FromRadiansPerSecondSquared(QuantityValue r #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(double revolutionsperminutepersecond) - { - double value = (double) revolutionsperminutepersecond; - return new RotationalAcceleration(((2*Math.PI)/60)*value); - } #else public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(QuantityValue revolutionsperminutepersecond) +#endif { double value = (double) revolutionsperminutepersecond; - return new RotationalAcceleration((((2*Math.PI)/60)*value)); + return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -279,18 +286,7 @@ public static RotationalAcceleration From(double value, RotationalAccelerationUn public static RotationalAcceleration From(QuantityValue value, RotationalAccelerationUnit fromUnit) #endif { - switch (fromUnit) - { - case RotationalAccelerationUnit.DegreePerSecondSquared: - return FromDegreesPerSecondSquared(value); - case RotationalAccelerationUnit.RadianPerSecondSquared: - return FromRadiansPerSecondSquared(value); - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: - return FromRevolutionsPerMinutePerSecond(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new RotationalAcceleration((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -307,18 +303,8 @@ public static RotationalAcceleration From(QuantityValue value, RotationalAcceler { return null; } - switch (fromUnit) - { - case RotationalAccelerationUnit.DegreePerSecondSquared: - return FromDegreesPerSecondSquared(value.Value); - case RotationalAccelerationUnit.RadianPerSecondSquared: - return FromRadiansPerSecondSquared(value.Value); - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: - return FromRevolutionsPerMinutePerSecond(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new RotationalAcceleration((double)value.Value, fromUnit); } #endif @@ -337,12 +323,29 @@ public static string GetAbbreviation(RotationalAccelerationUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(RotationalAccelerationUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + RotationalAccelerationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -353,37 +356,37 @@ public static string GetAbbreviation(RotationalAccelerationUnit unit, [CanBeNull #if !WINDOWS_UWP public static RotationalAcceleration operator -(RotationalAcceleration right) { - return new RotationalAcceleration(-right._radiansPerSecondSquared); + return new RotationalAcceleration(-right.Value, right.Unit); } public static RotationalAcceleration operator +(RotationalAcceleration left, RotationalAcceleration right) { - return new RotationalAcceleration(left._radiansPerSecondSquared + right._radiansPerSecondSquared); + return new RotationalAcceleration(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static RotationalAcceleration operator -(RotationalAcceleration left, RotationalAcceleration right) { - return new RotationalAcceleration(left._radiansPerSecondSquared - right._radiansPerSecondSquared); + return new RotationalAcceleration(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static RotationalAcceleration operator *(double left, RotationalAcceleration right) { - return new RotationalAcceleration(left*right._radiansPerSecondSquared); + return new RotationalAcceleration(left * right.Value, right.Unit); } public static RotationalAcceleration operator *(RotationalAcceleration left, double right) { - return new RotationalAcceleration(left._radiansPerSecondSquared*(double)right); + return new RotationalAcceleration(left.Value * right, left.Unit); } public static RotationalAcceleration operator /(RotationalAcceleration left, double right) { - return new RotationalAcceleration(left._radiansPerSecondSquared/(double)right); + return new RotationalAcceleration(left.Value / right, left.Unit); } public static double operator /(RotationalAcceleration left, RotationalAcceleration right) { - return Convert.ToDouble(left._radiansPerSecondSquared/right._radiansPerSecondSquared); + return left.RadiansPerSecondSquared / right.RadiansPerSecondSquared; } #endif @@ -406,43 +409,43 @@ public int CompareTo(object obj) #endif int CompareTo(RotationalAcceleration other) { - return _radiansPerSecondSquared.CompareTo(other._radiansPerSecondSquared); + return AsBaseUnitRadiansPerSecondSquared().CompareTo(other.AsBaseUnitRadiansPerSecondSquared()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(RotationalAcceleration left, RotationalAcceleration right) { - return left._radiansPerSecondSquared <= right._radiansPerSecondSquared; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(RotationalAcceleration left, RotationalAcceleration right) { - return left._radiansPerSecondSquared >= right._radiansPerSecondSquared; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(RotationalAcceleration left, RotationalAcceleration right) { - return left._radiansPerSecondSquared < right._radiansPerSecondSquared; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(RotationalAcceleration left, RotationalAcceleration right) { - return left._radiansPerSecondSquared > right._radiansPerSecondSquared; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(RotationalAcceleration left, RotationalAcceleration right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._radiansPerSecondSquared == right._radiansPerSecondSquared; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(RotationalAcceleration left, RotationalAcceleration right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._radiansPerSecondSquared != right._radiansPerSecondSquared; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -454,7 +457,7 @@ public override bool Equals(object obj) return false; } - return _radiansPerSecondSquared.Equals(((RotationalAcceleration) obj)._radiansPerSecondSquared); + return AsBaseUnitRadiansPerSecondSquared().Equals(((RotationalAcceleration) obj).AsBaseUnitRadiansPerSecondSquared()); } /// @@ -467,12 +470,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(RotationalAcceleration other, RotationalAcceleration maxError) { - return Math.Abs(_radiansPerSecondSquared - other._radiansPerSecondSquared) <= maxError._radiansPerSecondSquared; + return Math.Abs(AsBaseUnitRadiansPerSecondSquared() - other.AsBaseUnitRadiansPerSecondSquared()) <= maxError.AsBaseUnitRadiansPerSecondSquared(); } public override int GetHashCode() { - return _radiansPerSecondSquared.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -482,18 +485,21 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(RotationalAccelerationUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitRadiansPerSecondSquared(); + switch (unit) { - case RotationalAccelerationUnit.DegreePerSecondSquared: - return DegreesPerSecondSquared; - case RotationalAccelerationUnit.RadianPerSecondSquared: - return RadiansPerSecondSquared; - case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: - return RevolutionsPerMinutePerSecond; + case RotationalAccelerationUnit.DegreePerSecondSquared: return (180/Math.PI)*baseUnitValue; + case RotationalAccelerationUnit.RadianPerSecondSquared: return baseUnitValue; + case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return (60/(2*Math.PI))*baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -535,7 +541,11 @@ public static RotationalAcceleration Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -554,17 +564,24 @@ public static RotationalAcceleration Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static RotationalAcceleration Parse(string str, [CanBeNull] Culture culture) + public static RotationalAcceleration Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -590,16 +607,41 @@ public static bool TryParse([CanBeNull] string str, out RotationalAcceleration r /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out RotationalAcceleration result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out RotationalAcceleration result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -612,6 +654,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -625,11 +668,14 @@ public static RotationalAccelerationUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static RotationalAccelerationUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -638,6 +684,8 @@ public static RotationalAccelerationUnit ParseUnit(string str, [CanBeNull] strin /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -650,18 +698,18 @@ public static RotationalAccelerationUnit ParseUnit(string str, [CanBeNull] strin #else public #endif - static RotationalAccelerationUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static RotationalAccelerationUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == RotationalAccelerationUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalAccelerationUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -670,6 +718,7 @@ static RotationalAccelerationUnit ParseUnit(string str, IFormatProvider formatPr #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is RadianPerSecondSquared /// @@ -681,7 +730,7 @@ static RotationalAccelerationUnit ParseUnit(string str, IFormatProvider formatPr /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -698,74 +747,131 @@ public string ToString(RotationalAccelerationUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(RotationalAccelerationUnit unit, [CanBeNull] Culture culture) + public string ToString( + RotationalAccelerationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(RotationalAccelerationUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + RotationalAccelerationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(RotationalAccelerationUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + RotationalAccelerationUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of RotationalAcceleration /// - public static RotationalAcceleration MaxValue - { - get - { - return new RotationalAcceleration(double.MaxValue); - } - } + public static RotationalAcceleration MaxValue => new RotationalAcceleration(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of RotationalAcceleration /// - public static RotationalAcceleration MinValue + public static RotationalAcceleration MinValue => new RotationalAcceleration(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitRadiansPerSecondSquared() { - get + if (Unit == RotationalAccelerationUnit.RadianPerSecondSquared) { return _value; } + + switch (Unit) { - return new RotationalAcceleration(double.MinValue); - } - } - } + case RotationalAccelerationUnit.DegreePerSecondSquared: return (Math.PI/180)*_value; + case RotationalAccelerationUnit.RadianPerSecondSquared: return _value; + case RotationalAccelerationUnit.RevolutionPerMinutePerSecond: return ((2*Math.PI)/60)*_value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(RotationalAccelerationUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs index 0d93e3bfcb..7ef7ac10a9 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct RotationalSpeed : IComparable, IComparable - /// Base unit of RotationalSpeed. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly RotationalSpeedUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _radiansPerSecond; + public RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public RotationalSpeed() : this(0) + public RotationalSpeed() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public RotationalSpeed(double radianspersecond) { - _radiansPerSecond = Convert.ToDouble(radianspersecond); + _value = Convert.ToDouble(radianspersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + RotationalSpeed(double numericValue, RotationalSpeedUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit RadianPerSecond. + /// + /// Value assuming base unit RadianPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - RotationalSpeed(long radianspersecond) - { - _radiansPerSecond = Convert.ToDouble(radianspersecond); - } + RotationalSpeed(long radianspersecond) : this(Convert.ToDouble(radianspersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit RadianPerSecond. + /// + /// Value assuming base unit RadianPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - RotationalSpeed(decimal radianspersecond) - { - _radiansPerSecond = Convert.ToDouble(radianspersecond); - } + RotationalSpeed(decimal radianspersecond) : this(Convert.ToDouble(radianspersecond), BaseUnit) { } #region Properties @@ -119,128 +156,70 @@ public RotationalSpeed(double radianspersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static RotationalSpeedUnit BaseUnit - { - get { return RotationalSpeedUnit.RadianPerSecond; } - } + public static RotationalSpeedUnit BaseUnit => RotationalSpeedUnit.RadianPerSecond; /// /// All units of measurement for the RotationalSpeed quantity. /// public static RotationalSpeedUnit[] Units { get; } = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().ToArray(); - /// /// Get RotationalSpeed in CentiradiansPerSecond. /// - public double CentiradiansPerSecond - { - get { return (_radiansPerSecond) / 1e-2d; } - } - + public double CentiradiansPerSecond => As(RotationalSpeedUnit.CentiradianPerSecond); /// /// Get RotationalSpeed in DeciradiansPerSecond. /// - public double DeciradiansPerSecond - { - get { return (_radiansPerSecond) / 1e-1d; } - } - + public double DeciradiansPerSecond => As(RotationalSpeedUnit.DeciradianPerSecond); /// /// Get RotationalSpeed in DegreesPerMinute. /// - public double DegreesPerMinute - { - get { return (180*60/Math.PI)*_radiansPerSecond; } - } - + public double DegreesPerMinute => As(RotationalSpeedUnit.DegreePerMinute); /// /// Get RotationalSpeed in DegreesPerSecond. /// - public double DegreesPerSecond - { - get { return (180/Math.PI)*_radiansPerSecond; } - } - + public double DegreesPerSecond => As(RotationalSpeedUnit.DegreePerSecond); /// /// Get RotationalSpeed in MicrodegreesPerSecond. /// - public double MicrodegreesPerSecond - { - get { return ((180/Math.PI)*_radiansPerSecond) / 1e-6d; } - } - + public double MicrodegreesPerSecond => As(RotationalSpeedUnit.MicrodegreePerSecond); /// /// Get RotationalSpeed in MicroradiansPerSecond. /// - public double MicroradiansPerSecond - { - get { return (_radiansPerSecond) / 1e-6d; } - } - + public double MicroradiansPerSecond => As(RotationalSpeedUnit.MicroradianPerSecond); /// /// Get RotationalSpeed in MillidegreesPerSecond. /// - public double MillidegreesPerSecond - { - get { return ((180/Math.PI)*_radiansPerSecond) / 1e-3d; } - } - + public double MillidegreesPerSecond => As(RotationalSpeedUnit.MillidegreePerSecond); /// /// Get RotationalSpeed in MilliradiansPerSecond. /// - public double MilliradiansPerSecond - { - get { return (_radiansPerSecond) / 1e-3d; } - } - + public double MilliradiansPerSecond => As(RotationalSpeedUnit.MilliradianPerSecond); /// /// Get RotationalSpeed in NanodegreesPerSecond. /// - public double NanodegreesPerSecond - { - get { return ((180/Math.PI)*_radiansPerSecond) / 1e-9d; } - } - + public double NanodegreesPerSecond => As(RotationalSpeedUnit.NanodegreePerSecond); /// /// Get RotationalSpeed in NanoradiansPerSecond. /// - public double NanoradiansPerSecond - { - get { return (_radiansPerSecond) / 1e-9d; } - } - + public double NanoradiansPerSecond => As(RotationalSpeedUnit.NanoradianPerSecond); /// /// Get RotationalSpeed in RadiansPerSecond. /// - public double RadiansPerSecond - { - get { return _radiansPerSecond; } - } - + public double RadiansPerSecond => As(RotationalSpeedUnit.RadianPerSecond); /// /// Get RotationalSpeed in RevolutionsPerMinute. /// - public double RevolutionsPerMinute - { - get { return (_radiansPerSecond/6.2831853072)*60; } - } - + public double RevolutionsPerMinute => As(RotationalSpeedUnit.RevolutionPerMinute); /// /// Get RotationalSpeed in RevolutionsPerSecond. /// - public double RevolutionsPerSecond - { - get { return _radiansPerSecond/6.2831853072; } - } + public double RevolutionsPerSecond => As(RotationalSpeedUnit.RevolutionPerSecond); #endregion #region Static - public static RotationalSpeed Zero - { - get { return new RotationalSpeed(); } - } + public static RotationalSpeed Zero => new RotationalSpeed(0, BaseUnit); /// /// Get RotationalSpeed from CentiradiansPerSecond. @@ -248,17 +227,13 @@ public static RotationalSpeed Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromCentiradiansPerSecond(double centiradianspersecond) - { - double value = (double) centiradianspersecond; - return new RotationalSpeed((value) * 1e-2d); - } #else public static RotationalSpeed FromCentiradiansPerSecond(QuantityValue centiradianspersecond) +#endif { double value = (double) centiradianspersecond; - return new RotationalSpeed(((value) * 1e-2d)); + return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); } -#endif /// /// Get RotationalSpeed from DeciradiansPerSecond. @@ -266,17 +241,13 @@ public static RotationalSpeed FromCentiradiansPerSecond(QuantityValue centiradia #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromDeciradiansPerSecond(double deciradianspersecond) - { - double value = (double) deciradianspersecond; - return new RotationalSpeed((value) * 1e-1d); - } #else public static RotationalSpeed FromDeciradiansPerSecond(QuantityValue deciradianspersecond) +#endif { double value = (double) deciradianspersecond; - return new RotationalSpeed(((value) * 1e-1d)); + return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); } -#endif /// /// Get RotationalSpeed from DegreesPerMinute. @@ -284,17 +255,13 @@ public static RotationalSpeed FromDeciradiansPerSecond(QuantityValue deciradians #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromDegreesPerMinute(double degreesperminute) - { - double value = (double) degreesperminute; - return new RotationalSpeed((Math.PI/(180*60))*value); - } #else public static RotationalSpeed FromDegreesPerMinute(QuantityValue degreesperminute) +#endif { double value = (double) degreesperminute; - return new RotationalSpeed(((Math.PI/(180*60))*value)); + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); } -#endif /// /// Get RotationalSpeed from DegreesPerSecond. @@ -302,17 +269,13 @@ public static RotationalSpeed FromDegreesPerMinute(QuantityValue degreesperminut #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromDegreesPerSecond(double degreespersecond) - { - double value = (double) degreespersecond; - return new RotationalSpeed((Math.PI/180)*value); - } #else public static RotationalSpeed FromDegreesPerSecond(QuantityValue degreespersecond) +#endif { double value = (double) degreespersecond; - return new RotationalSpeed(((Math.PI/180)*value)); + return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); } -#endif /// /// Get RotationalSpeed from MicrodegreesPerSecond. @@ -320,17 +283,13 @@ public static RotationalSpeed FromDegreesPerSecond(QuantityValue degreespersecon #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromMicrodegreesPerSecond(double microdegreespersecond) - { - double value = (double) microdegreespersecond; - return new RotationalSpeed(((Math.PI/180)*value) * 1e-6d); - } #else public static RotationalSpeed FromMicrodegreesPerSecond(QuantityValue microdegreespersecond) +#endif { double value = (double) microdegreespersecond; - return new RotationalSpeed((((Math.PI/180)*value) * 1e-6d)); + return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); } -#endif /// /// Get RotationalSpeed from MicroradiansPerSecond. @@ -338,17 +297,13 @@ public static RotationalSpeed FromMicrodegreesPerSecond(QuantityValue microdegre #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromMicroradiansPerSecond(double microradianspersecond) - { - double value = (double) microradianspersecond; - return new RotationalSpeed((value) * 1e-6d); - } #else public static RotationalSpeed FromMicroradiansPerSecond(QuantityValue microradianspersecond) +#endif { double value = (double) microradianspersecond; - return new RotationalSpeed(((value) * 1e-6d)); + return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); } -#endif /// /// Get RotationalSpeed from MillidegreesPerSecond. @@ -356,17 +311,13 @@ public static RotationalSpeed FromMicroradiansPerSecond(QuantityValue microradia #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromMillidegreesPerSecond(double millidegreespersecond) - { - double value = (double) millidegreespersecond; - return new RotationalSpeed(((Math.PI/180)*value) * 1e-3d); - } #else public static RotationalSpeed FromMillidegreesPerSecond(QuantityValue millidegreespersecond) +#endif { double value = (double) millidegreespersecond; - return new RotationalSpeed((((Math.PI/180)*value) * 1e-3d)); + return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); } -#endif /// /// Get RotationalSpeed from MilliradiansPerSecond. @@ -374,17 +325,13 @@ public static RotationalSpeed FromMillidegreesPerSecond(QuantityValue millidegre #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromMilliradiansPerSecond(double milliradianspersecond) - { - double value = (double) milliradianspersecond; - return new RotationalSpeed((value) * 1e-3d); - } #else public static RotationalSpeed FromMilliradiansPerSecond(QuantityValue milliradianspersecond) +#endif { double value = (double) milliradianspersecond; - return new RotationalSpeed(((value) * 1e-3d)); + return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); } -#endif /// /// Get RotationalSpeed from NanodegreesPerSecond. @@ -392,17 +339,13 @@ public static RotationalSpeed FromMilliradiansPerSecond(QuantityValue milliradia #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromNanodegreesPerSecond(double nanodegreespersecond) - { - double value = (double) nanodegreespersecond; - return new RotationalSpeed(((Math.PI/180)*value) * 1e-9d); - } #else public static RotationalSpeed FromNanodegreesPerSecond(QuantityValue nanodegreespersecond) +#endif { double value = (double) nanodegreespersecond; - return new RotationalSpeed((((Math.PI/180)*value) * 1e-9d)); + return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); } -#endif /// /// Get RotationalSpeed from NanoradiansPerSecond. @@ -410,17 +353,13 @@ public static RotationalSpeed FromNanodegreesPerSecond(QuantityValue nanodegrees #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromNanoradiansPerSecond(double nanoradianspersecond) - { - double value = (double) nanoradianspersecond; - return new RotationalSpeed((value) * 1e-9d); - } #else public static RotationalSpeed FromNanoradiansPerSecond(QuantityValue nanoradianspersecond) +#endif { double value = (double) nanoradianspersecond; - return new RotationalSpeed(((value) * 1e-9d)); + return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); } -#endif /// /// Get RotationalSpeed from RadiansPerSecond. @@ -428,17 +367,13 @@ public static RotationalSpeed FromNanoradiansPerSecond(QuantityValue nanoradians #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromRadiansPerSecond(double radianspersecond) - { - double value = (double) radianspersecond; - return new RotationalSpeed(value); - } #else public static RotationalSpeed FromRadiansPerSecond(QuantityValue radianspersecond) +#endif { double value = (double) radianspersecond; - return new RotationalSpeed((value)); + return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); } -#endif /// /// Get RotationalSpeed from RevolutionsPerMinute. @@ -446,17 +381,13 @@ public static RotationalSpeed FromRadiansPerSecond(QuantityValue radianspersecon #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromRevolutionsPerMinute(double revolutionsperminute) - { - double value = (double) revolutionsperminute; - return new RotationalSpeed((value*6.2831853072)/60); - } #else public static RotationalSpeed FromRevolutionsPerMinute(QuantityValue revolutionsperminute) +#endif { double value = (double) revolutionsperminute; - return new RotationalSpeed(((value*6.2831853072)/60)); + return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); } -#endif /// /// Get RotationalSpeed from RevolutionsPerSecond. @@ -464,17 +395,13 @@ public static RotationalSpeed FromRevolutionsPerMinute(QuantityValue revolutions #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static RotationalSpeed FromRevolutionsPerSecond(double revolutionspersecond) - { - double value = (double) revolutionspersecond; - return new RotationalSpeed(value*6.2831853072); - } #else public static RotationalSpeed FromRevolutionsPerSecond(QuantityValue revolutionspersecond) +#endif { double value = (double) revolutionspersecond; - return new RotationalSpeed((value*6.2831853072)); + return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerSecond); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -689,38 +616,7 @@ public static RotationalSpeed From(double value, RotationalSpeedUnit fromUnit) public static RotationalSpeed From(QuantityValue value, RotationalSpeedUnit fromUnit) #endif { - switch (fromUnit) - { - case RotationalSpeedUnit.CentiradianPerSecond: - return FromCentiradiansPerSecond(value); - case RotationalSpeedUnit.DeciradianPerSecond: - return FromDeciradiansPerSecond(value); - case RotationalSpeedUnit.DegreePerMinute: - return FromDegreesPerMinute(value); - case RotationalSpeedUnit.DegreePerSecond: - return FromDegreesPerSecond(value); - case RotationalSpeedUnit.MicrodegreePerSecond: - return FromMicrodegreesPerSecond(value); - case RotationalSpeedUnit.MicroradianPerSecond: - return FromMicroradiansPerSecond(value); - case RotationalSpeedUnit.MillidegreePerSecond: - return FromMillidegreesPerSecond(value); - case RotationalSpeedUnit.MilliradianPerSecond: - return FromMilliradiansPerSecond(value); - case RotationalSpeedUnit.NanodegreePerSecond: - return FromNanodegreesPerSecond(value); - case RotationalSpeedUnit.NanoradianPerSecond: - return FromNanoradiansPerSecond(value); - case RotationalSpeedUnit.RadianPerSecond: - return FromRadiansPerSecond(value); - case RotationalSpeedUnit.RevolutionPerMinute: - return FromRevolutionsPerMinute(value); - case RotationalSpeedUnit.RevolutionPerSecond: - return FromRevolutionsPerSecond(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new RotationalSpeed((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -737,38 +633,8 @@ public static RotationalSpeed From(QuantityValue value, RotationalSpeedUnit from { return null; } - switch (fromUnit) - { - case RotationalSpeedUnit.CentiradianPerSecond: - return FromCentiradiansPerSecond(value.Value); - case RotationalSpeedUnit.DeciradianPerSecond: - return FromDeciradiansPerSecond(value.Value); - case RotationalSpeedUnit.DegreePerMinute: - return FromDegreesPerMinute(value.Value); - case RotationalSpeedUnit.DegreePerSecond: - return FromDegreesPerSecond(value.Value); - case RotationalSpeedUnit.MicrodegreePerSecond: - return FromMicrodegreesPerSecond(value.Value); - case RotationalSpeedUnit.MicroradianPerSecond: - return FromMicroradiansPerSecond(value.Value); - case RotationalSpeedUnit.MillidegreePerSecond: - return FromMillidegreesPerSecond(value.Value); - case RotationalSpeedUnit.MilliradianPerSecond: - return FromMilliradiansPerSecond(value.Value); - case RotationalSpeedUnit.NanodegreePerSecond: - return FromNanodegreesPerSecond(value.Value); - case RotationalSpeedUnit.NanoradianPerSecond: - return FromNanoradiansPerSecond(value.Value); - case RotationalSpeedUnit.RadianPerSecond: - return FromRadiansPerSecond(value.Value); - case RotationalSpeedUnit.RevolutionPerMinute: - return FromRevolutionsPerMinute(value.Value); - case RotationalSpeedUnit.RevolutionPerSecond: - return FromRevolutionsPerSecond(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new RotationalSpeed((double)value.Value, fromUnit); } #endif @@ -787,12 +653,29 @@ public static string GetAbbreviation(RotationalSpeedUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(RotationalSpeedUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + RotationalSpeedUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -803,37 +686,37 @@ public static string GetAbbreviation(RotationalSpeedUnit unit, [CanBeNull] Cultu #if !WINDOWS_UWP public static RotationalSpeed operator -(RotationalSpeed right) { - return new RotationalSpeed(-right._radiansPerSecond); + return new RotationalSpeed(-right.Value, right.Unit); } public static RotationalSpeed operator +(RotationalSpeed left, RotationalSpeed right) { - return new RotationalSpeed(left._radiansPerSecond + right._radiansPerSecond); + return new RotationalSpeed(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static RotationalSpeed operator -(RotationalSpeed left, RotationalSpeed right) { - return new RotationalSpeed(left._radiansPerSecond - right._radiansPerSecond); + return new RotationalSpeed(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static RotationalSpeed operator *(double left, RotationalSpeed right) { - return new RotationalSpeed(left*right._radiansPerSecond); + return new RotationalSpeed(left * right.Value, right.Unit); } public static RotationalSpeed operator *(RotationalSpeed left, double right) { - return new RotationalSpeed(left._radiansPerSecond*(double)right); + return new RotationalSpeed(left.Value * right, left.Unit); } public static RotationalSpeed operator /(RotationalSpeed left, double right) { - return new RotationalSpeed(left._radiansPerSecond/(double)right); + return new RotationalSpeed(left.Value / right, left.Unit); } public static double operator /(RotationalSpeed left, RotationalSpeed right) { - return Convert.ToDouble(left._radiansPerSecond/right._radiansPerSecond); + return left.RadiansPerSecond / right.RadiansPerSecond; } #endif @@ -856,43 +739,43 @@ public int CompareTo(object obj) #endif int CompareTo(RotationalSpeed other) { - return _radiansPerSecond.CompareTo(other._radiansPerSecond); + return AsBaseUnitRadiansPerSecond().CompareTo(other.AsBaseUnitRadiansPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(RotationalSpeed left, RotationalSpeed right) { - return left._radiansPerSecond <= right._radiansPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(RotationalSpeed left, RotationalSpeed right) { - return left._radiansPerSecond >= right._radiansPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(RotationalSpeed left, RotationalSpeed right) { - return left._radiansPerSecond < right._radiansPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(RotationalSpeed left, RotationalSpeed right) { - return left._radiansPerSecond > right._radiansPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(RotationalSpeed left, RotationalSpeed right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._radiansPerSecond == right._radiansPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(RotationalSpeed left, RotationalSpeed right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._radiansPerSecond != right._radiansPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -904,7 +787,7 @@ public override bool Equals(object obj) return false; } - return _radiansPerSecond.Equals(((RotationalSpeed) obj)._radiansPerSecond); + return AsBaseUnitRadiansPerSecond().Equals(((RotationalSpeed) obj).AsBaseUnitRadiansPerSecond()); } /// @@ -917,12 +800,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(RotationalSpeed other, RotationalSpeed maxError) { - return Math.Abs(_radiansPerSecond - other._radiansPerSecond) <= maxError._radiansPerSecond; + return Math.Abs(AsBaseUnitRadiansPerSecond() - other.AsBaseUnitRadiansPerSecond()) <= maxError.AsBaseUnitRadiansPerSecond(); } public override int GetHashCode() { - return _radiansPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -932,38 +815,31 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(RotationalSpeedUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitRadiansPerSecond(); + switch (unit) { - case RotationalSpeedUnit.CentiradianPerSecond: - return CentiradiansPerSecond; - case RotationalSpeedUnit.DeciradianPerSecond: - return DeciradiansPerSecond; - case RotationalSpeedUnit.DegreePerMinute: - return DegreesPerMinute; - case RotationalSpeedUnit.DegreePerSecond: - return DegreesPerSecond; - case RotationalSpeedUnit.MicrodegreePerSecond: - return MicrodegreesPerSecond; - case RotationalSpeedUnit.MicroradianPerSecond: - return MicroradiansPerSecond; - case RotationalSpeedUnit.MillidegreePerSecond: - return MillidegreesPerSecond; - case RotationalSpeedUnit.MilliradianPerSecond: - return MilliradiansPerSecond; - case RotationalSpeedUnit.NanodegreePerSecond: - return NanodegreesPerSecond; - case RotationalSpeedUnit.NanoradianPerSecond: - return NanoradiansPerSecond; - case RotationalSpeedUnit.RadianPerSecond: - return RadiansPerSecond; - case RotationalSpeedUnit.RevolutionPerMinute: - return RevolutionsPerMinute; - case RotationalSpeedUnit.RevolutionPerSecond: - return RevolutionsPerSecond; + case RotationalSpeedUnit.CentiradianPerSecond: return (baseUnitValue) / 1e-2d; + case RotationalSpeedUnit.DeciradianPerSecond: return (baseUnitValue) / 1e-1d; + case RotationalSpeedUnit.DegreePerMinute: return (180*60/Math.PI)*baseUnitValue; + case RotationalSpeedUnit.DegreePerSecond: return (180/Math.PI)*baseUnitValue; + case RotationalSpeedUnit.MicrodegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-6d; + case RotationalSpeedUnit.MicroradianPerSecond: return (baseUnitValue) / 1e-6d; + case RotationalSpeedUnit.MillidegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-3d; + case RotationalSpeedUnit.MilliradianPerSecond: return (baseUnitValue) / 1e-3d; + case RotationalSpeedUnit.NanodegreePerSecond: return ((180/Math.PI)*baseUnitValue) / 1e-9d; + case RotationalSpeedUnit.NanoradianPerSecond: return (baseUnitValue) / 1e-9d; + case RotationalSpeedUnit.RadianPerSecond: return baseUnitValue; + case RotationalSpeedUnit.RevolutionPerMinute: return (baseUnitValue/6.2831853072)*60; + case RotationalSpeedUnit.RevolutionPerSecond: return baseUnitValue/6.2831853072; default: throw new NotImplementedException("unit: " + unit); @@ -1005,7 +881,11 @@ public static RotationalSpeed Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1024,17 +904,24 @@ public static RotationalSpeed Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static RotationalSpeed Parse(string str, [CanBeNull] Culture culture) + public static RotationalSpeed Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1060,16 +947,41 @@ public static bool TryParse([CanBeNull] string str, out RotationalSpeed result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out RotationalSpeed result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out RotationalSpeed result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1082,6 +994,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1095,11 +1008,14 @@ public static RotationalSpeedUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static RotationalSpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1108,6 +1024,8 @@ public static RotationalSpeedUnit ParseUnit(string str, [CanBeNull] string cultu /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1120,18 +1038,18 @@ public static RotationalSpeedUnit ParseUnit(string str, [CanBeNull] string cultu #else public #endif - static RotationalSpeedUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static RotationalSpeedUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == RotationalSpeedUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalSpeedUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1140,6 +1058,7 @@ static RotationalSpeedUnit ParseUnit(string str, IFormatProvider formatProvider #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is RadianPerSecond /// @@ -1151,7 +1070,7 @@ static RotationalSpeedUnit ParseUnit(string str, IFormatProvider formatProvider /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1168,74 +1087,141 @@ public string ToString(RotationalSpeedUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(RotationalSpeedUnit unit, [CanBeNull] Culture culture) + public string ToString( + RotationalSpeedUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(RotationalSpeedUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + RotationalSpeedUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(RotationalSpeedUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + RotationalSpeedUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of RotationalSpeed /// - public static RotationalSpeed MaxValue - { - get - { - return new RotationalSpeed(double.MaxValue); - } - } + public static RotationalSpeed MaxValue => new RotationalSpeed(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of RotationalSpeed /// - public static RotationalSpeed MinValue + public static RotationalSpeed MinValue => new RotationalSpeed(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitRadiansPerSecond() { - get + if (Unit == RotationalSpeedUnit.RadianPerSecond) { return _value; } + + switch (Unit) { - return new RotationalSpeed(double.MinValue); - } - } - } + case RotationalSpeedUnit.CentiradianPerSecond: return (_value) * 1e-2d; + case RotationalSpeedUnit.DeciradianPerSecond: return (_value) * 1e-1d; + case RotationalSpeedUnit.DegreePerMinute: return (Math.PI/(180*60))*_value; + case RotationalSpeedUnit.DegreePerSecond: return (Math.PI/180)*_value; + case RotationalSpeedUnit.MicrodegreePerSecond: return ((Math.PI/180)*_value) * 1e-6d; + case RotationalSpeedUnit.MicroradianPerSecond: return (_value) * 1e-6d; + case RotationalSpeedUnit.MillidegreePerSecond: return ((Math.PI/180)*_value) * 1e-3d; + case RotationalSpeedUnit.MilliradianPerSecond: return (_value) * 1e-3d; + case RotationalSpeedUnit.NanodegreePerSecond: return ((Math.PI/180)*_value) * 1e-9d; + case RotationalSpeedUnit.NanoradianPerSecond: return (_value) * 1e-9d; + case RotationalSpeedUnit.RadianPerSecond: return _value; + case RotationalSpeedUnit.RevolutionPerMinute: return (_value*6.2831853072)/60; + case RotationalSpeedUnit.RevolutionPerSecond: return _value*6.2831853072; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(RotationalSpeedUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs index 3918442c69..49a20f694e 100644 --- a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct SolidAngle : IComparable, IComparable #endif { /// - /// Base unit of SolidAngle. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SolidAngleUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _steradians; + public SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public SolidAngle() : this(0) + public SolidAngle() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public SolidAngle(double steradians) { - _steradians = Convert.ToDouble(steradians); + _value = Convert.ToDouble(steradians); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + SolidAngle(double numericValue, SolidAngleUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Steradian. + /// + /// Value assuming base unit Steradian. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - SolidAngle(long steradians) - { - _steradians = Convert.ToDouble(steradians); - } + SolidAngle(long steradians) : this(Convert.ToDouble(steradians), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Steradian. + /// + /// Value assuming base unit Steradian. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - SolidAngle(decimal steradians) - { - _steradians = Convert.ToDouble(steradians); - } + SolidAngle(decimal steradians) : this(Convert.ToDouble(steradians), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public SolidAngle(double steradians) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static SolidAngleUnit BaseUnit - { - get { return SolidAngleUnit.Steradian; } - } + public static SolidAngleUnit BaseUnit => SolidAngleUnit.Steradian; /// /// All units of measurement for the SolidAngle quantity. /// public static SolidAngleUnit[] Units { get; } = Enum.GetValues(typeof(SolidAngleUnit)).Cast().ToArray(); - /// /// Get SolidAngle in Steradians. /// - public double Steradians - { - get { return _steradians; } - } + public double Steradians => As(SolidAngleUnit.Steradian); #endregion #region Static - public static SolidAngle Zero - { - get { return new SolidAngle(); } - } + public static SolidAngle Zero => new SolidAngle(0, BaseUnit); /// /// Get SolidAngle from Steradians. @@ -152,17 +179,13 @@ public static SolidAngle Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SolidAngle FromSteradians(double steradians) - { - double value = (double) steradians; - return new SolidAngle(value); - } #else public static SolidAngle FromSteradians(QuantityValue steradians) +#endif { double value = (double) steradians; - return new SolidAngle((value)); + return new SolidAngle(value, SolidAngleUnit.Steradian); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static SolidAngle From(double value, SolidAngleUnit fromUnit) public static SolidAngle From(QuantityValue value, SolidAngleUnit fromUnit) #endif { - switch (fromUnit) - { - case SolidAngleUnit.Steradian: - return FromSteradians(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new SolidAngle((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static SolidAngle From(QuantityValue value, SolidAngleUnit fromUnit) { return null; } - switch (fromUnit) - { - case SolidAngleUnit.Steradian: - return FromSteradians(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new SolidAngle((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(SolidAngleUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(SolidAngleUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + SolidAngleUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(SolidAngleUnit unit, [CanBeNull] Culture cu #if !WINDOWS_UWP public static SolidAngle operator -(SolidAngle right) { - return new SolidAngle(-right._steradians); + return new SolidAngle(-right.Value, right.Unit); } public static SolidAngle operator +(SolidAngle left, SolidAngle right) { - return new SolidAngle(left._steradians + right._steradians); + return new SolidAngle(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static SolidAngle operator -(SolidAngle left, SolidAngle right) { - return new SolidAngle(left._steradians - right._steradians); + return new SolidAngle(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static SolidAngle operator *(double left, SolidAngle right) { - return new SolidAngle(left*right._steradians); + return new SolidAngle(left * right.Value, right.Unit); } public static SolidAngle operator *(SolidAngle left, double right) { - return new SolidAngle(left._steradians*(double)right); + return new SolidAngle(left.Value * right, left.Unit); } public static SolidAngle operator /(SolidAngle left, double right) { - return new SolidAngle(left._steradians/(double)right); + return new SolidAngle(left.Value / right, left.Unit); } public static double operator /(SolidAngle left, SolidAngle right) { - return Convert.ToDouble(left._steradians/right._steradians); + return left.Steradians / right.Steradians; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(SolidAngle other) { - return _steradians.CompareTo(other._steradians); + return AsBaseUnitSteradians().CompareTo(other.AsBaseUnitSteradians()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(SolidAngle left, SolidAngle right) { - return left._steradians <= right._steradians; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(SolidAngle left, SolidAngle right) { - return left._steradians >= right._steradians; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(SolidAngle left, SolidAngle right) { - return left._steradians < right._steradians; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(SolidAngle left, SolidAngle right) { - return left._steradians > right._steradians; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(SolidAngle left, SolidAngle right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._steradians == right._steradians; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(SolidAngle left, SolidAngle right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._steradians != right._steradians; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _steradians.Equals(((SolidAngle) obj)._steradians); + return AsBaseUnitSteradians().Equals(((SolidAngle) obj).AsBaseUnitSteradians()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(SolidAngle other, SolidAngle maxError) { - return Math.Abs(_steradians - other._steradians) <= maxError._steradians; + return Math.Abs(AsBaseUnitSteradians() - other.AsBaseUnitSteradians()) <= maxError.AsBaseUnitSteradians(); } public override int GetHashCode() { - return _steradians.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(SolidAngleUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitSteradians(); + switch (unit) { - case SolidAngleUnit.Steradian: - return Steradians; + case SolidAngleUnit.Steradian: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static SolidAngle Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static SolidAngle Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static SolidAngle Parse(string str, [CanBeNull] Culture culture) + public static SolidAngle Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out SolidAngle result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out SolidAngle result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out SolidAngle result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static SolidAngleUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static SolidAngleUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static SolidAngleUnit ParseUnit(string str, [CanBeNull] string cultureNam /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static SolidAngleUnit ParseUnit(string str, [CanBeNull] string cultureNam #else public #endif - static SolidAngleUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static SolidAngleUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == SolidAngleUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SolidAngleUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static SolidAngleUnit ParseUnit(string str, IFormatProvider formatProvider = nul #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Steradian /// @@ -587,7 +662,7 @@ static SolidAngleUnit ParseUnit(string str, IFormatProvider formatProvider = nul /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(SolidAngleUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(SolidAngleUnit unit, [CanBeNull] Culture culture) + public string ToString( + SolidAngleUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(SolidAngleUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + SolidAngleUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(SolidAngleUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + SolidAngleUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of SolidAngle /// - public static SolidAngle MaxValue - { - get - { - return new SolidAngle(double.MaxValue); - } - } + public static SolidAngle MaxValue => new SolidAngle(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of SolidAngle /// - public static SolidAngle MinValue + public static SolidAngle MinValue => new SolidAngle(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitSteradians() { - get + if (Unit == SolidAngleUnit.Steradian) { return _value; } + + switch (Unit) { - return new SolidAngle(double.MinValue); - } - } - } + case SolidAngleUnit.Steradian: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(SolidAngleUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs index b4c4aa68c8..ab9dfc9d15 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct SpecificEnergy : IComparable, IComparable #endif { /// - /// Base unit of SpecificEnergy. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _joulesPerKilogram; + private readonly SpecificEnergyUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public SpecificEnergy() : this(0) + public SpecificEnergy() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public SpecificEnergy(double joulesperkilogram) { - _joulesPerKilogram = Convert.ToDouble(joulesperkilogram); + _value = Convert.ToDouble(joulesperkilogram); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + SpecificEnergy(double numericValue, SpecificEnergyUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit JoulePerKilogram. + /// + /// Value assuming base unit JoulePerKilogram. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - SpecificEnergy(long joulesperkilogram) - { - _joulesPerKilogram = Convert.ToDouble(joulesperkilogram); - } + SpecificEnergy(long joulesperkilogram) : this(Convert.ToDouble(joulesperkilogram), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit JoulePerKilogram. + /// + /// Value assuming base unit JoulePerKilogram. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - SpecificEnergy(decimal joulesperkilogram) - { - _joulesPerKilogram = Convert.ToDouble(joulesperkilogram); - } + SpecificEnergy(decimal joulesperkilogram) : this(Convert.ToDouble(joulesperkilogram), BaseUnit) { } #region Properties @@ -119,88 +156,50 @@ public SpecificEnergy(double joulesperkilogram) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static SpecificEnergyUnit BaseUnit - { - get { return SpecificEnergyUnit.JoulePerKilogram; } - } + public static SpecificEnergyUnit BaseUnit => SpecificEnergyUnit.JoulePerKilogram; /// /// All units of measurement for the SpecificEnergy quantity. /// public static SpecificEnergyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().ToArray(); - /// /// Get SpecificEnergy in CaloriesPerGram. /// - public double CaloriesPerGram - { - get { return _joulesPerKilogram/4.184e3; } - } - + public double CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram); /// /// Get SpecificEnergy in JoulesPerKilogram. /// - public double JoulesPerKilogram - { - get { return _joulesPerKilogram; } - } - + public double JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram); /// /// Get SpecificEnergy in KilocaloriesPerGram. /// - public double KilocaloriesPerGram - { - get { return (_joulesPerKilogram/4.184e3) / 1e3d; } - } - + public double KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram); /// /// Get SpecificEnergy in KilojoulesPerKilogram. /// - public double KilojoulesPerKilogram - { - get { return (_joulesPerKilogram) / 1e3d; } - } - + public double KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram); /// /// Get SpecificEnergy in KilowattHoursPerKilogram. /// - public double KilowattHoursPerKilogram - { - get { return (_joulesPerKilogram/3.6e3) / 1e3d; } - } - + public double KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram); /// /// Get SpecificEnergy in MegajoulesPerKilogram. /// - public double MegajoulesPerKilogram - { - get { return (_joulesPerKilogram) / 1e6d; } - } - + public double MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram); /// /// Get SpecificEnergy in MegawattHoursPerKilogram. /// - public double MegawattHoursPerKilogram - { - get { return (_joulesPerKilogram/3.6e3) / 1e6d; } - } - + public double MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram); /// /// Get SpecificEnergy in WattHoursPerKilogram. /// - public double WattHoursPerKilogram - { - get { return _joulesPerKilogram/3.6e3; } - } + public double WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram); #endregion #region Static - public static SpecificEnergy Zero - { - get { return new SpecificEnergy(); } - } + public static SpecificEnergy Zero => new SpecificEnergy(0, BaseUnit); /// /// Get SpecificEnergy from CaloriesPerGram. @@ -208,17 +207,13 @@ public static SpecificEnergy Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEnergy FromCaloriesPerGram(double caloriespergram) - { - double value = (double) caloriespergram; - return new SpecificEnergy(value*4.184e3); - } #else public static SpecificEnergy FromCaloriesPerGram(QuantityValue caloriespergram) +#endif { double value = (double) caloriespergram; - return new SpecificEnergy((value*4.184e3)); + return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); } -#endif /// /// Get SpecificEnergy from JoulesPerKilogram. @@ -226,17 +221,13 @@ public static SpecificEnergy FromCaloriesPerGram(QuantityValue caloriespergram) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEnergy FromJoulesPerKilogram(double joulesperkilogram) - { - double value = (double) joulesperkilogram; - return new SpecificEnergy(value); - } #else public static SpecificEnergy FromJoulesPerKilogram(QuantityValue joulesperkilogram) +#endif { double value = (double) joulesperkilogram; - return new SpecificEnergy((value)); + return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); } -#endif /// /// Get SpecificEnergy from KilocaloriesPerGram. @@ -244,17 +235,13 @@ public static SpecificEnergy FromJoulesPerKilogram(QuantityValue joulesperkilogr #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEnergy FromKilocaloriesPerGram(double kilocaloriespergram) - { - double value = (double) kilocaloriespergram; - return new SpecificEnergy((value*4.184e3) * 1e3d); - } #else public static SpecificEnergy FromKilocaloriesPerGram(QuantityValue kilocaloriespergram) +#endif { double value = (double) kilocaloriespergram; - return new SpecificEnergy(((value*4.184e3) * 1e3d)); + return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); } -#endif /// /// Get SpecificEnergy from KilojoulesPerKilogram. @@ -262,17 +249,13 @@ public static SpecificEnergy FromKilocaloriesPerGram(QuantityValue kilocaloriesp #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEnergy FromKilojoulesPerKilogram(double kilojoulesperkilogram) - { - double value = (double) kilojoulesperkilogram; - return new SpecificEnergy((value) * 1e3d); - } #else public static SpecificEnergy FromKilojoulesPerKilogram(QuantityValue kilojoulesperkilogram) +#endif { double value = (double) kilojoulesperkilogram; - return new SpecificEnergy(((value) * 1e3d)); + return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); } -#endif /// /// Get SpecificEnergy from KilowattHoursPerKilogram. @@ -280,17 +263,13 @@ public static SpecificEnergy FromKilojoulesPerKilogram(QuantityValue kilojoulesp #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEnergy FromKilowattHoursPerKilogram(double kilowatthoursperkilogram) - { - double value = (double) kilowatthoursperkilogram; - return new SpecificEnergy((value*3.6e3) * 1e3d); - } #else public static SpecificEnergy FromKilowattHoursPerKilogram(QuantityValue kilowatthoursperkilogram) +#endif { double value = (double) kilowatthoursperkilogram; - return new SpecificEnergy(((value*3.6e3) * 1e3d)); + return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); } -#endif /// /// Get SpecificEnergy from MegajoulesPerKilogram. @@ -298,17 +277,13 @@ public static SpecificEnergy FromKilowattHoursPerKilogram(QuantityValue kilowatt #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEnergy FromMegajoulesPerKilogram(double megajoulesperkilogram) - { - double value = (double) megajoulesperkilogram; - return new SpecificEnergy((value) * 1e6d); - } #else public static SpecificEnergy FromMegajoulesPerKilogram(QuantityValue megajoulesperkilogram) +#endif { double value = (double) megajoulesperkilogram; - return new SpecificEnergy(((value) * 1e6d)); + return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); } -#endif /// /// Get SpecificEnergy from MegawattHoursPerKilogram. @@ -316,17 +291,13 @@ public static SpecificEnergy FromMegajoulesPerKilogram(QuantityValue megajoulesp #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEnergy FromMegawattHoursPerKilogram(double megawatthoursperkilogram) - { - double value = (double) megawatthoursperkilogram; - return new SpecificEnergy((value*3.6e3) * 1e6d); - } #else public static SpecificEnergy FromMegawattHoursPerKilogram(QuantityValue megawatthoursperkilogram) +#endif { double value = (double) megawatthoursperkilogram; - return new SpecificEnergy(((value*3.6e3) * 1e6d)); + return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); } -#endif /// /// Get SpecificEnergy from WattHoursPerKilogram. @@ -334,17 +305,13 @@ public static SpecificEnergy FromMegawattHoursPerKilogram(QuantityValue megawatt #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEnergy FromWattHoursPerKilogram(double watthoursperkilogram) - { - double value = (double) watthoursperkilogram; - return new SpecificEnergy(value*3.6e3); - } #else public static SpecificEnergy FromWattHoursPerKilogram(QuantityValue watthoursperkilogram) +#endif { double value = (double) watthoursperkilogram; - return new SpecificEnergy((value*3.6e3)); + return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerKilogram); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -484,28 +451,7 @@ public static SpecificEnergy From(double value, SpecificEnergyUnit fromUnit) public static SpecificEnergy From(QuantityValue value, SpecificEnergyUnit fromUnit) #endif { - switch (fromUnit) - { - case SpecificEnergyUnit.CaloriePerGram: - return FromCaloriesPerGram(value); - case SpecificEnergyUnit.JoulePerKilogram: - return FromJoulesPerKilogram(value); - case SpecificEnergyUnit.KilocaloriePerGram: - return FromKilocaloriesPerGram(value); - case SpecificEnergyUnit.KilojoulePerKilogram: - return FromKilojoulesPerKilogram(value); - case SpecificEnergyUnit.KilowattHourPerKilogram: - return FromKilowattHoursPerKilogram(value); - case SpecificEnergyUnit.MegajoulePerKilogram: - return FromMegajoulesPerKilogram(value); - case SpecificEnergyUnit.MegawattHourPerKilogram: - return FromMegawattHoursPerKilogram(value); - case SpecificEnergyUnit.WattHourPerKilogram: - return FromWattHoursPerKilogram(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new SpecificEnergy((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -522,28 +468,8 @@ public static SpecificEnergy From(QuantityValue value, SpecificEnergyUnit fromUn { return null; } - switch (fromUnit) - { - case SpecificEnergyUnit.CaloriePerGram: - return FromCaloriesPerGram(value.Value); - case SpecificEnergyUnit.JoulePerKilogram: - return FromJoulesPerKilogram(value.Value); - case SpecificEnergyUnit.KilocaloriePerGram: - return FromKilocaloriesPerGram(value.Value); - case SpecificEnergyUnit.KilojoulePerKilogram: - return FromKilojoulesPerKilogram(value.Value); - case SpecificEnergyUnit.KilowattHourPerKilogram: - return FromKilowattHoursPerKilogram(value.Value); - case SpecificEnergyUnit.MegajoulePerKilogram: - return FromMegajoulesPerKilogram(value.Value); - case SpecificEnergyUnit.MegawattHourPerKilogram: - return FromMegawattHoursPerKilogram(value.Value); - case SpecificEnergyUnit.WattHourPerKilogram: - return FromWattHoursPerKilogram(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new SpecificEnergy((double)value.Value, fromUnit); } #endif @@ -562,12 +488,29 @@ public static string GetAbbreviation(SpecificEnergyUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(SpecificEnergyUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + SpecificEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -578,37 +521,37 @@ public static string GetAbbreviation(SpecificEnergyUnit unit, [CanBeNull] Cultur #if !WINDOWS_UWP public static SpecificEnergy operator -(SpecificEnergy right) { - return new SpecificEnergy(-right._joulesPerKilogram); + return new SpecificEnergy(-right.Value, right.Unit); } public static SpecificEnergy operator +(SpecificEnergy left, SpecificEnergy right) { - return new SpecificEnergy(left._joulesPerKilogram + right._joulesPerKilogram); + return new SpecificEnergy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static SpecificEnergy operator -(SpecificEnergy left, SpecificEnergy right) { - return new SpecificEnergy(left._joulesPerKilogram - right._joulesPerKilogram); + return new SpecificEnergy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static SpecificEnergy operator *(double left, SpecificEnergy right) { - return new SpecificEnergy(left*right._joulesPerKilogram); + return new SpecificEnergy(left * right.Value, right.Unit); } public static SpecificEnergy operator *(SpecificEnergy left, double right) { - return new SpecificEnergy(left._joulesPerKilogram*(double)right); + return new SpecificEnergy(left.Value * right, left.Unit); } public static SpecificEnergy operator /(SpecificEnergy left, double right) { - return new SpecificEnergy(left._joulesPerKilogram/(double)right); + return new SpecificEnergy(left.Value / right, left.Unit); } public static double operator /(SpecificEnergy left, SpecificEnergy right) { - return Convert.ToDouble(left._joulesPerKilogram/right._joulesPerKilogram); + return left.JoulesPerKilogram / right.JoulesPerKilogram; } #endif @@ -631,43 +574,43 @@ public int CompareTo(object obj) #endif int CompareTo(SpecificEnergy other) { - return _joulesPerKilogram.CompareTo(other._joulesPerKilogram); + return AsBaseUnitJoulesPerKilogram().CompareTo(other.AsBaseUnitJoulesPerKilogram()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(SpecificEnergy left, SpecificEnergy right) { - return left._joulesPerKilogram <= right._joulesPerKilogram; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(SpecificEnergy left, SpecificEnergy right) { - return left._joulesPerKilogram >= right._joulesPerKilogram; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(SpecificEnergy left, SpecificEnergy right) { - return left._joulesPerKilogram < right._joulesPerKilogram; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(SpecificEnergy left, SpecificEnergy right) { - return left._joulesPerKilogram > right._joulesPerKilogram; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(SpecificEnergy left, SpecificEnergy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerKilogram == right._joulesPerKilogram; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(SpecificEnergy left, SpecificEnergy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerKilogram != right._joulesPerKilogram; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -679,7 +622,7 @@ public override bool Equals(object obj) return false; } - return _joulesPerKilogram.Equals(((SpecificEnergy) obj)._joulesPerKilogram); + return AsBaseUnitJoulesPerKilogram().Equals(((SpecificEnergy) obj).AsBaseUnitJoulesPerKilogram()); } /// @@ -692,12 +635,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(SpecificEnergy other, SpecificEnergy maxError) { - return Math.Abs(_joulesPerKilogram - other._joulesPerKilogram) <= maxError._joulesPerKilogram; + return Math.Abs(AsBaseUnitJoulesPerKilogram() - other.AsBaseUnitJoulesPerKilogram()) <= maxError.AsBaseUnitJoulesPerKilogram(); } public override int GetHashCode() { - return _joulesPerKilogram.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -707,28 +650,26 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(SpecificEnergyUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitJoulesPerKilogram(); + switch (unit) { - case SpecificEnergyUnit.CaloriePerGram: - return CaloriesPerGram; - case SpecificEnergyUnit.JoulePerKilogram: - return JoulesPerKilogram; - case SpecificEnergyUnit.KilocaloriePerGram: - return KilocaloriesPerGram; - case SpecificEnergyUnit.KilojoulePerKilogram: - return KilojoulesPerKilogram; - case SpecificEnergyUnit.KilowattHourPerKilogram: - return KilowattHoursPerKilogram; - case SpecificEnergyUnit.MegajoulePerKilogram: - return MegajoulesPerKilogram; - case SpecificEnergyUnit.MegawattHourPerKilogram: - return MegawattHoursPerKilogram; - case SpecificEnergyUnit.WattHourPerKilogram: - return WattHoursPerKilogram; + case SpecificEnergyUnit.CaloriePerGram: return baseUnitValue/4.184e3; + case SpecificEnergyUnit.JoulePerKilogram: return baseUnitValue; + case SpecificEnergyUnit.KilocaloriePerGram: return (baseUnitValue/4.184e3) / 1e3d; + case SpecificEnergyUnit.KilojoulePerKilogram: return (baseUnitValue) / 1e3d; + case SpecificEnergyUnit.KilowattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e3d; + case SpecificEnergyUnit.MegajoulePerKilogram: return (baseUnitValue) / 1e6d; + case SpecificEnergyUnit.MegawattHourPerKilogram: return (baseUnitValue/3.6e3) / 1e6d; + case SpecificEnergyUnit.WattHourPerKilogram: return baseUnitValue/3.6e3; default: throw new NotImplementedException("unit: " + unit); @@ -770,7 +711,11 @@ public static SpecificEnergy Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -789,17 +734,24 @@ public static SpecificEnergy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static SpecificEnergy Parse(string str, [CanBeNull] Culture culture) + public static SpecificEnergy Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -825,16 +777,41 @@ public static bool TryParse([CanBeNull] string str, out SpecificEnergy result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out SpecificEnergy result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out SpecificEnergy result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -847,6 +824,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -860,11 +838,14 @@ public static SpecificEnergyUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static SpecificEnergyUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -873,6 +854,8 @@ public static SpecificEnergyUnit ParseUnit(string str, [CanBeNull] string cultur /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -885,18 +868,18 @@ public static SpecificEnergyUnit ParseUnit(string str, [CanBeNull] string cultur #else public #endif - static SpecificEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static SpecificEnergyUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == SpecificEnergyUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificEnergyUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -905,6 +888,7 @@ static SpecificEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is JoulePerKilogram /// @@ -916,7 +900,7 @@ static SpecificEnergyUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -933,74 +917,136 @@ public string ToString(SpecificEnergyUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(SpecificEnergyUnit unit, [CanBeNull] Culture culture) + public string ToString( + SpecificEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(SpecificEnergyUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + SpecificEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(SpecificEnergyUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + SpecificEnergyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of SpecificEnergy /// - public static SpecificEnergy MaxValue - { - get - { - return new SpecificEnergy(double.MaxValue); - } - } + public static SpecificEnergy MaxValue => new SpecificEnergy(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of SpecificEnergy /// - public static SpecificEnergy MinValue + public static SpecificEnergy MinValue => new SpecificEnergy(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitJoulesPerKilogram() { - get + if (Unit == SpecificEnergyUnit.JoulePerKilogram) { return _value; } + + switch (Unit) { - return new SpecificEnergy(double.MinValue); - } - } - } + case SpecificEnergyUnit.CaloriePerGram: return _value*4.184e3; + case SpecificEnergyUnit.JoulePerKilogram: return _value; + case SpecificEnergyUnit.KilocaloriePerGram: return (_value*4.184e3) * 1e3d; + case SpecificEnergyUnit.KilojoulePerKilogram: return (_value) * 1e3d; + case SpecificEnergyUnit.KilowattHourPerKilogram: return (_value*3.6e3) * 1e3d; + case SpecificEnergyUnit.MegajoulePerKilogram: return (_value) * 1e6d; + case SpecificEnergyUnit.MegawattHourPerKilogram: return (_value*3.6e3) * 1e6d; + case SpecificEnergyUnit.WattHourPerKilogram: return _value*3.6e3; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(SpecificEnergyUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs index cbb3edd65e..7db24a51d1 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct SpecificEntropy : IComparable, IComparable - /// Base unit of SpecificEntropy. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _joulesPerKilogramKelvin; + private readonly SpecificEntropyUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public SpecificEntropy() : this(0) + public SpecificEntropy() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public SpecificEntropy(double joulesperkilogramkelvin) { - _joulesPerKilogramKelvin = Convert.ToDouble(joulesperkilogramkelvin); + _value = Convert.ToDouble(joulesperkilogramkelvin); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + SpecificEntropy(double numericValue, SpecificEntropyUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit JoulePerKilogramKelvin. + /// + /// Value assuming base unit JoulePerKilogramKelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - SpecificEntropy(long joulesperkilogramkelvin) - { - _joulesPerKilogramKelvin = Convert.ToDouble(joulesperkilogramkelvin); - } + SpecificEntropy(long joulesperkilogramkelvin) : this(Convert.ToDouble(joulesperkilogramkelvin), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit JoulePerKilogramKelvin. + /// + /// Value assuming base unit JoulePerKilogramKelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - SpecificEntropy(decimal joulesperkilogramkelvin) - { - _joulesPerKilogramKelvin = Convert.ToDouble(joulesperkilogramkelvin); - } + SpecificEntropy(decimal joulesperkilogramkelvin) : this(Convert.ToDouble(joulesperkilogramkelvin), BaseUnit) { } #region Properties @@ -119,88 +156,50 @@ public SpecificEntropy(double joulesperkilogramkelvin) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static SpecificEntropyUnit BaseUnit - { - get { return SpecificEntropyUnit.JoulePerKilogramKelvin; } - } + public static SpecificEntropyUnit BaseUnit => SpecificEntropyUnit.JoulePerKilogramKelvin; /// /// All units of measurement for the SpecificEntropy quantity. /// public static SpecificEntropyUnit[] Units { get; } = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().ToArray(); - /// /// Get SpecificEntropy in CaloriesPerGramKelvin. /// - public double CaloriesPerGramKelvin - { - get { return _joulesPerKilogramKelvin/4.184e3; } - } - + public double CaloriesPerGramKelvin => As(SpecificEntropyUnit.CaloriePerGramKelvin); /// /// Get SpecificEntropy in JoulesPerKilogramDegreeCelsius. /// - public double JoulesPerKilogramDegreeCelsius - { - get { return _joulesPerKilogramKelvin; } - } - + public double JoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); /// /// Get SpecificEntropy in JoulesPerKilogramKelvin. /// - public double JoulesPerKilogramKelvin - { - get { return _joulesPerKilogramKelvin; } - } - + public double JoulesPerKilogramKelvin => As(SpecificEntropyUnit.JoulePerKilogramKelvin); /// /// Get SpecificEntropy in KilocaloriesPerGramKelvin. /// - public double KilocaloriesPerGramKelvin - { - get { return (_joulesPerKilogramKelvin/4.184e3) / 1e3d; } - } - + public double KilocaloriesPerGramKelvin => As(SpecificEntropyUnit.KilocaloriePerGramKelvin); /// /// Get SpecificEntropy in KilojoulesPerKilogramDegreeCelsius. /// - public double KilojoulesPerKilogramDegreeCelsius - { - get { return (_joulesPerKilogramKelvin) / 1e3d; } - } - + public double KilojoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); /// /// Get SpecificEntropy in KilojoulesPerKilogramKelvin. /// - public double KilojoulesPerKilogramKelvin - { - get { return (_joulesPerKilogramKelvin) / 1e3d; } - } - + public double KilojoulesPerKilogramKelvin => As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); /// /// Get SpecificEntropy in MegajoulesPerKilogramDegreeCelsius. /// - public double MegajoulesPerKilogramDegreeCelsius - { - get { return (_joulesPerKilogramKelvin) / 1e6d; } - } - + public double MegajoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); /// /// Get SpecificEntropy in MegajoulesPerKilogramKelvin. /// - public double MegajoulesPerKilogramKelvin - { - get { return (_joulesPerKilogramKelvin) / 1e6d; } - } + public double MegajoulesPerKilogramKelvin => As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); #endregion #region Static - public static SpecificEntropy Zero - { - get { return new SpecificEntropy(); } - } + public static SpecificEntropy Zero => new SpecificEntropy(0, BaseUnit); /// /// Get SpecificEntropy from CaloriesPerGramKelvin. @@ -208,17 +207,13 @@ public static SpecificEntropy Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEntropy FromCaloriesPerGramKelvin(double caloriespergramkelvin) - { - double value = (double) caloriespergramkelvin; - return new SpecificEntropy(value*4.184e3); - } #else public static SpecificEntropy FromCaloriesPerGramKelvin(QuantityValue caloriespergramkelvin) +#endif { double value = (double) caloriespergramkelvin; - return new SpecificEntropy((value*4.184e3)); + return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); } -#endif /// /// Get SpecificEntropy from JoulesPerKilogramDegreeCelsius. @@ -226,17 +221,13 @@ public static SpecificEntropy FromCaloriesPerGramKelvin(QuantityValue caloriespe #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(double joulesperkilogramdegreecelsius) - { - double value = (double) joulesperkilogramdegreecelsius; - return new SpecificEntropy(value); - } #else public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(QuantityValue joulesperkilogramdegreecelsius) +#endif { double value = (double) joulesperkilogramdegreecelsius; - return new SpecificEntropy((value)); + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); } -#endif /// /// Get SpecificEntropy from JoulesPerKilogramKelvin. @@ -244,17 +235,13 @@ public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(QuantityValue j #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEntropy FromJoulesPerKilogramKelvin(double joulesperkilogramkelvin) - { - double value = (double) joulesperkilogramkelvin; - return new SpecificEntropy(value); - } #else public static SpecificEntropy FromJoulesPerKilogramKelvin(QuantityValue joulesperkilogramkelvin) +#endif { double value = (double) joulesperkilogramkelvin; - return new SpecificEntropy((value)); + return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); } -#endif /// /// Get SpecificEntropy from KilocaloriesPerGramKelvin. @@ -262,17 +249,13 @@ public static SpecificEntropy FromJoulesPerKilogramKelvin(QuantityValue joulespe #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEntropy FromKilocaloriesPerGramKelvin(double kilocaloriespergramkelvin) - { - double value = (double) kilocaloriespergramkelvin; - return new SpecificEntropy((value*4.184e3) * 1e3d); - } #else public static SpecificEntropy FromKilocaloriesPerGramKelvin(QuantityValue kilocaloriespergramkelvin) +#endif { double value = (double) kilocaloriespergramkelvin; - return new SpecificEntropy(((value*4.184e3) * 1e3d)); + return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); } -#endif /// /// Get SpecificEntropy from KilojoulesPerKilogramDegreeCelsius. @@ -280,17 +263,13 @@ public static SpecificEntropy FromKilocaloriesPerGramKelvin(QuantityValue kiloca #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(double kilojoulesperkilogramdegreecelsius) - { - double value = (double) kilojoulesperkilogramdegreecelsius; - return new SpecificEntropy((value) * 1e3d); - } #else public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(QuantityValue kilojoulesperkilogramdegreecelsius) +#endif { double value = (double) kilojoulesperkilogramdegreecelsius; - return new SpecificEntropy(((value) * 1e3d)); + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); } -#endif /// /// Get SpecificEntropy from KilojoulesPerKilogramKelvin. @@ -298,17 +277,13 @@ public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(QuantityVal #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEntropy FromKilojoulesPerKilogramKelvin(double kilojoulesperkilogramkelvin) - { - double value = (double) kilojoulesperkilogramkelvin; - return new SpecificEntropy((value) * 1e3d); - } #else public static SpecificEntropy FromKilojoulesPerKilogramKelvin(QuantityValue kilojoulesperkilogramkelvin) +#endif { double value = (double) kilojoulesperkilogramkelvin; - return new SpecificEntropy(((value) * 1e3d)); + return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); } -#endif /// /// Get SpecificEntropy from MegajoulesPerKilogramDegreeCelsius. @@ -316,17 +291,13 @@ public static SpecificEntropy FromKilojoulesPerKilogramKelvin(QuantityValue kilo #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(double megajoulesperkilogramdegreecelsius) - { - double value = (double) megajoulesperkilogramdegreecelsius; - return new SpecificEntropy((value) * 1e6d); - } #else public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(QuantityValue megajoulesperkilogramdegreecelsius) +#endif { double value = (double) megajoulesperkilogramdegreecelsius; - return new SpecificEntropy(((value) * 1e6d)); + return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); } -#endif /// /// Get SpecificEntropy from MegajoulesPerKilogramKelvin. @@ -334,17 +305,13 @@ public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(QuantityVal #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificEntropy FromMegajoulesPerKilogramKelvin(double megajoulesperkilogramkelvin) - { - double value = (double) megajoulesperkilogramkelvin; - return new SpecificEntropy((value) * 1e6d); - } #else public static SpecificEntropy FromMegajoulesPerKilogramKelvin(QuantityValue megajoulesperkilogramkelvin) +#endif { double value = (double) megajoulesperkilogramkelvin; - return new SpecificEntropy(((value) * 1e6d)); + return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramKelvin); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -484,28 +451,7 @@ public static SpecificEntropy From(double value, SpecificEntropyUnit fromUnit) public static SpecificEntropy From(QuantityValue value, SpecificEntropyUnit fromUnit) #endif { - switch (fromUnit) - { - case SpecificEntropyUnit.CaloriePerGramKelvin: - return FromCaloriesPerGramKelvin(value); - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: - return FromJoulesPerKilogramDegreeCelsius(value); - case SpecificEntropyUnit.JoulePerKilogramKelvin: - return FromJoulesPerKilogramKelvin(value); - case SpecificEntropyUnit.KilocaloriePerGramKelvin: - return FromKilocaloriesPerGramKelvin(value); - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: - return FromKilojoulesPerKilogramDegreeCelsius(value); - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: - return FromKilojoulesPerKilogramKelvin(value); - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: - return FromMegajoulesPerKilogramDegreeCelsius(value); - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: - return FromMegajoulesPerKilogramKelvin(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new SpecificEntropy((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -522,28 +468,8 @@ public static SpecificEntropy From(QuantityValue value, SpecificEntropyUnit from { return null; } - switch (fromUnit) - { - case SpecificEntropyUnit.CaloriePerGramKelvin: - return FromCaloriesPerGramKelvin(value.Value); - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: - return FromJoulesPerKilogramDegreeCelsius(value.Value); - case SpecificEntropyUnit.JoulePerKilogramKelvin: - return FromJoulesPerKilogramKelvin(value.Value); - case SpecificEntropyUnit.KilocaloriePerGramKelvin: - return FromKilocaloriesPerGramKelvin(value.Value); - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: - return FromKilojoulesPerKilogramDegreeCelsius(value.Value); - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: - return FromKilojoulesPerKilogramKelvin(value.Value); - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: - return FromMegajoulesPerKilogramDegreeCelsius(value.Value); - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: - return FromMegajoulesPerKilogramKelvin(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new SpecificEntropy((double)value.Value, fromUnit); } #endif @@ -562,12 +488,29 @@ public static string GetAbbreviation(SpecificEntropyUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(SpecificEntropyUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + SpecificEntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -578,37 +521,37 @@ public static string GetAbbreviation(SpecificEntropyUnit unit, [CanBeNull] Cultu #if !WINDOWS_UWP public static SpecificEntropy operator -(SpecificEntropy right) { - return new SpecificEntropy(-right._joulesPerKilogramKelvin); + return new SpecificEntropy(-right.Value, right.Unit); } public static SpecificEntropy operator +(SpecificEntropy left, SpecificEntropy right) { - return new SpecificEntropy(left._joulesPerKilogramKelvin + right._joulesPerKilogramKelvin); + return new SpecificEntropy(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static SpecificEntropy operator -(SpecificEntropy left, SpecificEntropy right) { - return new SpecificEntropy(left._joulesPerKilogramKelvin - right._joulesPerKilogramKelvin); + return new SpecificEntropy(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static SpecificEntropy operator *(double left, SpecificEntropy right) { - return new SpecificEntropy(left*right._joulesPerKilogramKelvin); + return new SpecificEntropy(left * right.Value, right.Unit); } public static SpecificEntropy operator *(SpecificEntropy left, double right) { - return new SpecificEntropy(left._joulesPerKilogramKelvin*(double)right); + return new SpecificEntropy(left.Value * right, left.Unit); } public static SpecificEntropy operator /(SpecificEntropy left, double right) { - return new SpecificEntropy(left._joulesPerKilogramKelvin/(double)right); + return new SpecificEntropy(left.Value / right, left.Unit); } public static double operator /(SpecificEntropy left, SpecificEntropy right) { - return Convert.ToDouble(left._joulesPerKilogramKelvin/right._joulesPerKilogramKelvin); + return left.JoulesPerKilogramKelvin / right.JoulesPerKilogramKelvin; } #endif @@ -631,43 +574,43 @@ public int CompareTo(object obj) #endif int CompareTo(SpecificEntropy other) { - return _joulesPerKilogramKelvin.CompareTo(other._joulesPerKilogramKelvin); + return AsBaseUnitJoulesPerKilogramKelvin().CompareTo(other.AsBaseUnitJoulesPerKilogramKelvin()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(SpecificEntropy left, SpecificEntropy right) { - return left._joulesPerKilogramKelvin <= right._joulesPerKilogramKelvin; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(SpecificEntropy left, SpecificEntropy right) { - return left._joulesPerKilogramKelvin >= right._joulesPerKilogramKelvin; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(SpecificEntropy left, SpecificEntropy right) { - return left._joulesPerKilogramKelvin < right._joulesPerKilogramKelvin; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(SpecificEntropy left, SpecificEntropy right) { - return left._joulesPerKilogramKelvin > right._joulesPerKilogramKelvin; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(SpecificEntropy left, SpecificEntropy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerKilogramKelvin == right._joulesPerKilogramKelvin; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(SpecificEntropy left, SpecificEntropy right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._joulesPerKilogramKelvin != right._joulesPerKilogramKelvin; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -679,7 +622,7 @@ public override bool Equals(object obj) return false; } - return _joulesPerKilogramKelvin.Equals(((SpecificEntropy) obj)._joulesPerKilogramKelvin); + return AsBaseUnitJoulesPerKilogramKelvin().Equals(((SpecificEntropy) obj).AsBaseUnitJoulesPerKilogramKelvin()); } /// @@ -692,12 +635,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(SpecificEntropy other, SpecificEntropy maxError) { - return Math.Abs(_joulesPerKilogramKelvin - other._joulesPerKilogramKelvin) <= maxError._joulesPerKilogramKelvin; + return Math.Abs(AsBaseUnitJoulesPerKilogramKelvin() - other.AsBaseUnitJoulesPerKilogramKelvin()) <= maxError.AsBaseUnitJoulesPerKilogramKelvin(); } public override int GetHashCode() { - return _joulesPerKilogramKelvin.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -707,28 +650,26 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(SpecificEntropyUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitJoulesPerKilogramKelvin(); + switch (unit) { - case SpecificEntropyUnit.CaloriePerGramKelvin: - return CaloriesPerGramKelvin; - case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: - return JoulesPerKilogramDegreeCelsius; - case SpecificEntropyUnit.JoulePerKilogramKelvin: - return JoulesPerKilogramKelvin; - case SpecificEntropyUnit.KilocaloriePerGramKelvin: - return KilocaloriesPerGramKelvin; - case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: - return KilojoulesPerKilogramDegreeCelsius; - case SpecificEntropyUnit.KilojoulePerKilogramKelvin: - return KilojoulesPerKilogramKelvin; - case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: - return MegajoulesPerKilogramDegreeCelsius; - case SpecificEntropyUnit.MegajoulePerKilogramKelvin: - return MegajoulesPerKilogramKelvin; + case SpecificEntropyUnit.CaloriePerGramKelvin: return baseUnitValue/4.184e3; + case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return baseUnitValue; + case SpecificEntropyUnit.JoulePerKilogramKelvin: return baseUnitValue; + case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (baseUnitValue/4.184e3) / 1e3d; + case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e3d; + case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (baseUnitValue) / 1e3d; + case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (baseUnitValue) / 1e6d; + case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (baseUnitValue) / 1e6d; default: throw new NotImplementedException("unit: " + unit); @@ -770,7 +711,11 @@ public static SpecificEntropy Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -789,17 +734,24 @@ public static SpecificEntropy Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static SpecificEntropy Parse(string str, [CanBeNull] Culture culture) + public static SpecificEntropy Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -825,16 +777,41 @@ public static bool TryParse([CanBeNull] string str, out SpecificEntropy result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out SpecificEntropy result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out SpecificEntropy result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -847,6 +824,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -860,11 +838,14 @@ public static SpecificEntropyUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static SpecificEntropyUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -873,6 +854,8 @@ public static SpecificEntropyUnit ParseUnit(string str, [CanBeNull] string cultu /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -885,18 +868,18 @@ public static SpecificEntropyUnit ParseUnit(string str, [CanBeNull] string cultu #else public #endif - static SpecificEntropyUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static SpecificEntropyUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == SpecificEntropyUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificEntropyUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -905,6 +888,7 @@ static SpecificEntropyUnit ParseUnit(string str, IFormatProvider formatProvider #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is JoulePerKilogramKelvin /// @@ -916,7 +900,7 @@ static SpecificEntropyUnit ParseUnit(string str, IFormatProvider formatProvider /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -933,74 +917,136 @@ public string ToString(SpecificEntropyUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(SpecificEntropyUnit unit, [CanBeNull] Culture culture) + public string ToString( + SpecificEntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(SpecificEntropyUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + SpecificEntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(SpecificEntropyUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + SpecificEntropyUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of SpecificEntropy /// - public static SpecificEntropy MaxValue - { - get - { - return new SpecificEntropy(double.MaxValue); - } - } + public static SpecificEntropy MaxValue => new SpecificEntropy(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of SpecificEntropy /// - public static SpecificEntropy MinValue + public static SpecificEntropy MinValue => new SpecificEntropy(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitJoulesPerKilogramKelvin() { - get + if (Unit == SpecificEntropyUnit.JoulePerKilogramKelvin) { return _value; } + + switch (Unit) { - return new SpecificEntropy(double.MinValue); - } - } - } + case SpecificEntropyUnit.CaloriePerGramKelvin: return _value*4.184e3; + case SpecificEntropyUnit.JoulePerKilogramDegreeCelsius: return _value; + case SpecificEntropyUnit.JoulePerKilogramKelvin: return _value; + case SpecificEntropyUnit.KilocaloriePerGramKelvin: return (_value*4.184e3) * 1e3d; + case SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius: return (_value) * 1e3d; + case SpecificEntropyUnit.KilojoulePerKilogramKelvin: return (_value) * 1e3d; + case SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius: return (_value) * 1e6d; + case SpecificEntropyUnit.MegajoulePerKilogramKelvin: return (_value) * 1e6d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(SpecificEntropyUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs index 803f523786..275409db13 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct SpecificVolume : IComparable, IComparable #endif { /// - /// Base unit of SpecificVolume. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificVolumeUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _cubicMetersPerKilogram; + public SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public SpecificVolume() : this(0) + public SpecificVolume() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public SpecificVolume(double cubicmetersperkilogram) { - _cubicMetersPerKilogram = Convert.ToDouble(cubicmetersperkilogram); + _value = Convert.ToDouble(cubicmetersperkilogram); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + SpecificVolume(double numericValue, SpecificVolumeUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit CubicMeterPerKilogram. + /// + /// Value assuming base unit CubicMeterPerKilogram. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - SpecificVolume(long cubicmetersperkilogram) - { - _cubicMetersPerKilogram = Convert.ToDouble(cubicmetersperkilogram); - } + SpecificVolume(long cubicmetersperkilogram) : this(Convert.ToDouble(cubicmetersperkilogram), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit CubicMeterPerKilogram. + /// + /// Value assuming base unit CubicMeterPerKilogram. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - SpecificVolume(decimal cubicmetersperkilogram) - { - _cubicMetersPerKilogram = Convert.ToDouble(cubicmetersperkilogram); - } + SpecificVolume(decimal cubicmetersperkilogram) : this(Convert.ToDouble(cubicmetersperkilogram), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public SpecificVolume(double cubicmetersperkilogram) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static SpecificVolumeUnit BaseUnit - { - get { return SpecificVolumeUnit.CubicMeterPerKilogram; } - } + public static SpecificVolumeUnit BaseUnit => SpecificVolumeUnit.CubicMeterPerKilogram; /// /// All units of measurement for the SpecificVolume quantity. /// public static SpecificVolumeUnit[] Units { get; } = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().ToArray(); - /// /// Get SpecificVolume in CubicMetersPerKilogram. /// - public double CubicMetersPerKilogram - { - get { return _cubicMetersPerKilogram; } - } + public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); #endregion #region Static - public static SpecificVolume Zero - { - get { return new SpecificVolume(); } - } + public static SpecificVolume Zero => new SpecificVolume(0, BaseUnit); /// /// Get SpecificVolume from CubicMetersPerKilogram. @@ -152,17 +179,13 @@ public static SpecificVolume Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificVolume FromCubicMetersPerKilogram(double cubicmetersperkilogram) - { - double value = (double) cubicmetersperkilogram; - return new SpecificVolume(value); - } #else public static SpecificVolume FromCubicMetersPerKilogram(QuantityValue cubicmetersperkilogram) +#endif { double value = (double) cubicmetersperkilogram; - return new SpecificVolume((value)); + return new SpecificVolume(value, SpecificVolumeUnit.CubicMeterPerKilogram); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static SpecificVolume From(double value, SpecificVolumeUnit fromUnit) public static SpecificVolume From(QuantityValue value, SpecificVolumeUnit fromUnit) #endif { - switch (fromUnit) - { - case SpecificVolumeUnit.CubicMeterPerKilogram: - return FromCubicMetersPerKilogram(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new SpecificVolume((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static SpecificVolume From(QuantityValue value, SpecificVolumeUnit fromUn { return null; } - switch (fromUnit) - { - case SpecificVolumeUnit.CubicMeterPerKilogram: - return FromCubicMetersPerKilogram(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new SpecificVolume((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(SpecificVolumeUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(SpecificVolumeUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + SpecificVolumeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(SpecificVolumeUnit unit, [CanBeNull] Cultur #if !WINDOWS_UWP public static SpecificVolume operator -(SpecificVolume right) { - return new SpecificVolume(-right._cubicMetersPerKilogram); + return new SpecificVolume(-right.Value, right.Unit); } public static SpecificVolume operator +(SpecificVolume left, SpecificVolume right) { - return new SpecificVolume(left._cubicMetersPerKilogram + right._cubicMetersPerKilogram); + return new SpecificVolume(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static SpecificVolume operator -(SpecificVolume left, SpecificVolume right) { - return new SpecificVolume(left._cubicMetersPerKilogram - right._cubicMetersPerKilogram); + return new SpecificVolume(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static SpecificVolume operator *(double left, SpecificVolume right) { - return new SpecificVolume(left*right._cubicMetersPerKilogram); + return new SpecificVolume(left * right.Value, right.Unit); } public static SpecificVolume operator *(SpecificVolume left, double right) { - return new SpecificVolume(left._cubicMetersPerKilogram*(double)right); + return new SpecificVolume(left.Value * right, left.Unit); } public static SpecificVolume operator /(SpecificVolume left, double right) { - return new SpecificVolume(left._cubicMetersPerKilogram/(double)right); + return new SpecificVolume(left.Value / right, left.Unit); } public static double operator /(SpecificVolume left, SpecificVolume right) { - return Convert.ToDouble(left._cubicMetersPerKilogram/right._cubicMetersPerKilogram); + return left.CubicMetersPerKilogram / right.CubicMetersPerKilogram; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(SpecificVolume other) { - return _cubicMetersPerKilogram.CompareTo(other._cubicMetersPerKilogram); + return AsBaseUnitCubicMetersPerKilogram().CompareTo(other.AsBaseUnitCubicMetersPerKilogram()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(SpecificVolume left, SpecificVolume right) { - return left._cubicMetersPerKilogram <= right._cubicMetersPerKilogram; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(SpecificVolume left, SpecificVolume right) { - return left._cubicMetersPerKilogram >= right._cubicMetersPerKilogram; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(SpecificVolume left, SpecificVolume right) { - return left._cubicMetersPerKilogram < right._cubicMetersPerKilogram; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(SpecificVolume left, SpecificVolume right) { - return left._cubicMetersPerKilogram > right._cubicMetersPerKilogram; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(SpecificVolume left, SpecificVolume right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._cubicMetersPerKilogram == right._cubicMetersPerKilogram; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(SpecificVolume left, SpecificVolume right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._cubicMetersPerKilogram != right._cubicMetersPerKilogram; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _cubicMetersPerKilogram.Equals(((SpecificVolume) obj)._cubicMetersPerKilogram); + return AsBaseUnitCubicMetersPerKilogram().Equals(((SpecificVolume) obj).AsBaseUnitCubicMetersPerKilogram()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(SpecificVolume other, SpecificVolume maxError) { - return Math.Abs(_cubicMetersPerKilogram - other._cubicMetersPerKilogram) <= maxError._cubicMetersPerKilogram; + return Math.Abs(AsBaseUnitCubicMetersPerKilogram() - other.AsBaseUnitCubicMetersPerKilogram()) <= maxError.AsBaseUnitCubicMetersPerKilogram(); } public override int GetHashCode() { - return _cubicMetersPerKilogram.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(SpecificVolumeUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitCubicMetersPerKilogram(); + switch (unit) { - case SpecificVolumeUnit.CubicMeterPerKilogram: - return CubicMetersPerKilogram; + case SpecificVolumeUnit.CubicMeterPerKilogram: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static SpecificVolume Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static SpecificVolume Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static SpecificVolume Parse(string str, [CanBeNull] Culture culture) + public static SpecificVolume Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out SpecificVolume result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out SpecificVolume result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out SpecificVolume result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static SpecificVolumeUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static SpecificVolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static SpecificVolumeUnit ParseUnit(string str, [CanBeNull] string cultur /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static SpecificVolumeUnit ParseUnit(string str, [CanBeNull] string cultur #else public #endif - static SpecificVolumeUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static SpecificVolumeUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == SpecificVolumeUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificVolumeUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static SpecificVolumeUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is CubicMeterPerKilogram /// @@ -587,7 +662,7 @@ static SpecificVolumeUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(SpecificVolumeUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(SpecificVolumeUnit unit, [CanBeNull] Culture culture) + public string ToString( + SpecificVolumeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(SpecificVolumeUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + SpecificVolumeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(SpecificVolumeUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + SpecificVolumeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of SpecificVolume /// - public static SpecificVolume MaxValue - { - get - { - return new SpecificVolume(double.MaxValue); - } - } + public static SpecificVolume MaxValue => new SpecificVolume(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of SpecificVolume /// - public static SpecificVolume MinValue + public static SpecificVolume MinValue => new SpecificVolume(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitCubicMetersPerKilogram() { - get + if (Unit == SpecificVolumeUnit.CubicMeterPerKilogram) { return _value; } + + switch (Unit) { - return new SpecificVolume(double.MinValue); - } - } - } + case SpecificVolumeUnit.CubicMeterPerKilogram: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(SpecificVolumeUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs index e81661a5c6..75fa56b632 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct SpecificWeight : IComparable, IComparable #endif { /// - /// Base unit of SpecificWeight. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpecificWeightUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _newtonsPerCubicMeter; + public SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public SpecificWeight() : this(0) + public SpecificWeight() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public SpecificWeight(double newtonspercubicmeter) { - _newtonsPerCubicMeter = Convert.ToDouble(newtonspercubicmeter); + _value = Convert.ToDouble(newtonspercubicmeter); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + SpecificWeight(double numericValue, SpecificWeightUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit NewtonPerCubicMeter. + /// + /// Value assuming base unit NewtonPerCubicMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - SpecificWeight(long newtonspercubicmeter) - { - _newtonsPerCubicMeter = Convert.ToDouble(newtonspercubicmeter); - } + SpecificWeight(long newtonspercubicmeter) : this(Convert.ToDouble(newtonspercubicmeter), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit NewtonPerCubicMeter. + /// + /// Value assuming base unit NewtonPerCubicMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - SpecificWeight(decimal newtonspercubicmeter) - { - _newtonsPerCubicMeter = Convert.ToDouble(newtonspercubicmeter); - } + SpecificWeight(decimal newtonspercubicmeter) : this(Convert.ToDouble(newtonspercubicmeter), BaseUnit) { } #region Properties @@ -119,152 +156,82 @@ public SpecificWeight(double newtonspercubicmeter) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static SpecificWeightUnit BaseUnit - { - get { return SpecificWeightUnit.NewtonPerCubicMeter; } - } + public static SpecificWeightUnit BaseUnit => SpecificWeightUnit.NewtonPerCubicMeter; /// /// All units of measurement for the SpecificWeight quantity. /// public static SpecificWeightUnit[] Units { get; } = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().ToArray(); - /// /// Get SpecificWeight in KilogramsForcePerCubicCentimeter. /// - public double KilogramsForcePerCubicCentimeter - { - get { return _newtonsPerCubicMeter*1.01971619222242E-07; } - } - + public double KilogramsForcePerCubicCentimeter => As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); /// /// Get SpecificWeight in KilogramsForcePerCubicMeter. /// - public double KilogramsForcePerCubicMeter - { - get { return _newtonsPerCubicMeter*0.101971619222242; } - } - + public double KilogramsForcePerCubicMeter => As(SpecificWeightUnit.KilogramForcePerCubicMeter); /// /// Get SpecificWeight in KilogramsForcePerCubicMillimeter. /// - public double KilogramsForcePerCubicMillimeter - { - get { return _newtonsPerCubicMeter*1.01971619222242E-10; } - } - + public double KilogramsForcePerCubicMillimeter => As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); /// /// Get SpecificWeight in KilonewtonsPerCubicCentimeter. /// - public double KilonewtonsPerCubicCentimeter - { - get { return (_newtonsPerCubicMeter*0.000001) / 1e3d; } - } - + public double KilonewtonsPerCubicCentimeter => As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); /// /// Get SpecificWeight in KilonewtonsPerCubicMeter. /// - public double KilonewtonsPerCubicMeter - { - get { return (_newtonsPerCubicMeter) / 1e3d; } - } - + public double KilonewtonsPerCubicMeter => As(SpecificWeightUnit.KilonewtonPerCubicMeter); /// /// Get SpecificWeight in KilonewtonsPerCubicMillimeter. /// - public double KilonewtonsPerCubicMillimeter - { - get { return (_newtonsPerCubicMeter*0.000000001) / 1e3d; } - } - + public double KilonewtonsPerCubicMillimeter => As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); /// /// Get SpecificWeight in KilopoundsForcePerCubicFoot. /// - public double KilopoundsForcePerCubicFoot - { - get { return (_newtonsPerCubicMeter*0.00636587980366089) / 1e3d; } - } - + public double KilopoundsForcePerCubicFoot => As(SpecificWeightUnit.KilopoundForcePerCubicFoot); /// /// Get SpecificWeight in KilopoundsForcePerCubicInch. /// - public double KilopoundsForcePerCubicInch - { - get { return (_newtonsPerCubicMeter*3.68395821971116E-06) / 1e3d; } - } - + public double KilopoundsForcePerCubicInch => As(SpecificWeightUnit.KilopoundForcePerCubicInch); /// /// Get SpecificWeight in NewtonsPerCubicCentimeter. /// - public double NewtonsPerCubicCentimeter - { - get { return _newtonsPerCubicMeter*0.000001; } - } - + public double NewtonsPerCubicCentimeter => As(SpecificWeightUnit.NewtonPerCubicCentimeter); /// /// Get SpecificWeight in NewtonsPerCubicMeter. /// - public double NewtonsPerCubicMeter - { - get { return _newtonsPerCubicMeter; } - } - + public double NewtonsPerCubicMeter => As(SpecificWeightUnit.NewtonPerCubicMeter); /// /// Get SpecificWeight in NewtonsPerCubicMillimeter. /// - public double NewtonsPerCubicMillimeter - { - get { return _newtonsPerCubicMeter*0.000000001; } - } - + public double NewtonsPerCubicMillimeter => As(SpecificWeightUnit.NewtonPerCubicMillimeter); /// /// Get SpecificWeight in PoundsForcePerCubicFoot. /// - public double PoundsForcePerCubicFoot - { - get { return _newtonsPerCubicMeter*0.00636587980366089; } - } - + public double PoundsForcePerCubicFoot => As(SpecificWeightUnit.PoundForcePerCubicFoot); /// /// Get SpecificWeight in PoundsForcePerCubicInch. /// - public double PoundsForcePerCubicInch - { - get { return _newtonsPerCubicMeter*3.68395821971116E-06; } - } - + public double PoundsForcePerCubicInch => As(SpecificWeightUnit.PoundForcePerCubicInch); /// /// Get SpecificWeight in TonnesForcePerCubicCentimeter. /// - public double TonnesForcePerCubicCentimeter - { - get { return _newtonsPerCubicMeter*1.01971619222242E-10; } - } - + public double TonnesForcePerCubicCentimeter => As(SpecificWeightUnit.TonneForcePerCubicCentimeter); /// /// Get SpecificWeight in TonnesForcePerCubicMeter. /// - public double TonnesForcePerCubicMeter - { - get { return _newtonsPerCubicMeter*0.000101971619222242; } - } - + public double TonnesForcePerCubicMeter => As(SpecificWeightUnit.TonneForcePerCubicMeter); /// /// Get SpecificWeight in TonnesForcePerCubicMillimeter. /// - public double TonnesForcePerCubicMillimeter - { - get { return _newtonsPerCubicMeter*1.01971619222242E-13; } - } + public double TonnesForcePerCubicMillimeter => As(SpecificWeightUnit.TonneForcePerCubicMillimeter); #endregion #region Static - public static SpecificWeight Zero - { - get { return new SpecificWeight(); } - } + public static SpecificWeight Zero => new SpecificWeight(0, BaseUnit); /// /// Get SpecificWeight from KilogramsForcePerCubicCentimeter. @@ -272,17 +239,13 @@ public static SpecificWeight Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromKilogramsForcePerCubicCentimeter(double kilogramsforcepercubiccentimeter) - { - double value = (double) kilogramsforcepercubiccentimeter; - return new SpecificWeight(value*9806650.19960652); - } #else public static SpecificWeight FromKilogramsForcePerCubicCentimeter(QuantityValue kilogramsforcepercubiccentimeter) +#endif { double value = (double) kilogramsforcepercubiccentimeter; - return new SpecificWeight((value*9806650.19960652)); + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); } -#endif /// /// Get SpecificWeight from KilogramsForcePerCubicMeter. @@ -290,17 +253,13 @@ public static SpecificWeight FromKilogramsForcePerCubicCentimeter(QuantityValue #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromKilogramsForcePerCubicMeter(double kilogramsforcepercubicmeter) - { - double value = (double) kilogramsforcepercubicmeter; - return new SpecificWeight(value*9.80665019960652); - } #else public static SpecificWeight FromKilogramsForcePerCubicMeter(QuantityValue kilogramsforcepercubicmeter) +#endif { double value = (double) kilogramsforcepercubicmeter; - return new SpecificWeight((value*9.80665019960652)); + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); } -#endif /// /// Get SpecificWeight from KilogramsForcePerCubicMillimeter. @@ -308,17 +267,13 @@ public static SpecificWeight FromKilogramsForcePerCubicMeter(QuantityValue kilog #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromKilogramsForcePerCubicMillimeter(double kilogramsforcepercubicmillimeter) - { - double value = (double) kilogramsforcepercubicmillimeter; - return new SpecificWeight(value*9806650199.60653); - } #else public static SpecificWeight FromKilogramsForcePerCubicMillimeter(QuantityValue kilogramsforcepercubicmillimeter) +#endif { double value = (double) kilogramsforcepercubicmillimeter; - return new SpecificWeight((value*9806650199.60653)); + return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); } -#endif /// /// Get SpecificWeight from KilonewtonsPerCubicCentimeter. @@ -326,17 +281,13 @@ public static SpecificWeight FromKilogramsForcePerCubicMillimeter(QuantityValue #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromKilonewtonsPerCubicCentimeter(double kilonewtonspercubiccentimeter) - { - double value = (double) kilonewtonspercubiccentimeter; - return new SpecificWeight((value*1000000) * 1e3d); - } #else public static SpecificWeight FromKilonewtonsPerCubicCentimeter(QuantityValue kilonewtonspercubiccentimeter) +#endif { double value = (double) kilonewtonspercubiccentimeter; - return new SpecificWeight(((value*1000000) * 1e3d)); + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); } -#endif /// /// Get SpecificWeight from KilonewtonsPerCubicMeter. @@ -344,17 +295,13 @@ public static SpecificWeight FromKilonewtonsPerCubicCentimeter(QuantityValue kil #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromKilonewtonsPerCubicMeter(double kilonewtonspercubicmeter) - { - double value = (double) kilonewtonspercubicmeter; - return new SpecificWeight((value) * 1e3d); - } #else public static SpecificWeight FromKilonewtonsPerCubicMeter(QuantityValue kilonewtonspercubicmeter) +#endif { double value = (double) kilonewtonspercubicmeter; - return new SpecificWeight(((value) * 1e3d)); + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); } -#endif /// /// Get SpecificWeight from KilonewtonsPerCubicMillimeter. @@ -362,17 +309,13 @@ public static SpecificWeight FromKilonewtonsPerCubicMeter(QuantityValue kilonewt #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromKilonewtonsPerCubicMillimeter(double kilonewtonspercubicmillimeter) - { - double value = (double) kilonewtonspercubicmillimeter; - return new SpecificWeight((value*1000000000) * 1e3d); - } #else public static SpecificWeight FromKilonewtonsPerCubicMillimeter(QuantityValue kilonewtonspercubicmillimeter) +#endif { double value = (double) kilonewtonspercubicmillimeter; - return new SpecificWeight(((value*1000000000) * 1e3d)); + return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); } -#endif /// /// Get SpecificWeight from KilopoundsForcePerCubicFoot. @@ -380,17 +323,13 @@ public static SpecificWeight FromKilonewtonsPerCubicMillimeter(QuantityValue kil #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromKilopoundsForcePerCubicFoot(double kilopoundsforcepercubicfoot) - { - double value = (double) kilopoundsforcepercubicfoot; - return new SpecificWeight((value*157.087477433193) * 1e3d); - } #else public static SpecificWeight FromKilopoundsForcePerCubicFoot(QuantityValue kilopoundsforcepercubicfoot) +#endif { double value = (double) kilopoundsforcepercubicfoot; - return new SpecificWeight(((value*157.087477433193) * 1e3d)); + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); } -#endif /// /// Get SpecificWeight from KilopoundsForcePerCubicInch. @@ -398,17 +337,13 @@ public static SpecificWeight FromKilopoundsForcePerCubicFoot(QuantityValue kilop #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromKilopoundsForcePerCubicInch(double kilopoundsforcepercubicinch) - { - double value = (double) kilopoundsforcepercubicinch; - return new SpecificWeight((value*271447.161004558) * 1e3d); - } #else public static SpecificWeight FromKilopoundsForcePerCubicInch(QuantityValue kilopoundsforcepercubicinch) +#endif { double value = (double) kilopoundsforcepercubicinch; - return new SpecificWeight(((value*271447.161004558) * 1e3d)); + return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); } -#endif /// /// Get SpecificWeight from NewtonsPerCubicCentimeter. @@ -416,17 +351,13 @@ public static SpecificWeight FromKilopoundsForcePerCubicInch(QuantityValue kilop #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromNewtonsPerCubicCentimeter(double newtonspercubiccentimeter) - { - double value = (double) newtonspercubiccentimeter; - return new SpecificWeight(value*1000000); - } #else public static SpecificWeight FromNewtonsPerCubicCentimeter(QuantityValue newtonspercubiccentimeter) +#endif { double value = (double) newtonspercubiccentimeter; - return new SpecificWeight((value*1000000)); + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); } -#endif /// /// Get SpecificWeight from NewtonsPerCubicMeter. @@ -434,17 +365,13 @@ public static SpecificWeight FromNewtonsPerCubicCentimeter(QuantityValue newtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromNewtonsPerCubicMeter(double newtonspercubicmeter) - { - double value = (double) newtonspercubicmeter; - return new SpecificWeight(value); - } #else public static SpecificWeight FromNewtonsPerCubicMeter(QuantityValue newtonspercubicmeter) +#endif { double value = (double) newtonspercubicmeter; - return new SpecificWeight((value)); + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); } -#endif /// /// Get SpecificWeight from NewtonsPerCubicMillimeter. @@ -452,17 +379,13 @@ public static SpecificWeight FromNewtonsPerCubicMeter(QuantityValue newtonspercu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromNewtonsPerCubicMillimeter(double newtonspercubicmillimeter) - { - double value = (double) newtonspercubicmillimeter; - return new SpecificWeight(value*1000000000); - } #else public static SpecificWeight FromNewtonsPerCubicMillimeter(QuantityValue newtonspercubicmillimeter) +#endif { double value = (double) newtonspercubicmillimeter; - return new SpecificWeight((value*1000000000)); + return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); } -#endif /// /// Get SpecificWeight from PoundsForcePerCubicFoot. @@ -470,17 +393,13 @@ public static SpecificWeight FromNewtonsPerCubicMillimeter(QuantityValue newtons #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromPoundsForcePerCubicFoot(double poundsforcepercubicfoot) - { - double value = (double) poundsforcepercubicfoot; - return new SpecificWeight(value*157.087477433193); - } #else public static SpecificWeight FromPoundsForcePerCubicFoot(QuantityValue poundsforcepercubicfoot) +#endif { double value = (double) poundsforcepercubicfoot; - return new SpecificWeight((value*157.087477433193)); + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); } -#endif /// /// Get SpecificWeight from PoundsForcePerCubicInch. @@ -488,17 +407,13 @@ public static SpecificWeight FromPoundsForcePerCubicFoot(QuantityValue poundsfor #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromPoundsForcePerCubicInch(double poundsforcepercubicinch) - { - double value = (double) poundsforcepercubicinch; - return new SpecificWeight(value*271447.161004558); - } #else public static SpecificWeight FromPoundsForcePerCubicInch(QuantityValue poundsforcepercubicinch) +#endif { double value = (double) poundsforcepercubicinch; - return new SpecificWeight((value*271447.161004558)); + return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); } -#endif /// /// Get SpecificWeight from TonnesForcePerCubicCentimeter. @@ -506,17 +421,13 @@ public static SpecificWeight FromPoundsForcePerCubicInch(QuantityValue poundsfor #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromTonnesForcePerCubicCentimeter(double tonnesforcepercubiccentimeter) - { - double value = (double) tonnesforcepercubiccentimeter; - return new SpecificWeight(value*9806650199.60653); - } #else public static SpecificWeight FromTonnesForcePerCubicCentimeter(QuantityValue tonnesforcepercubiccentimeter) +#endif { double value = (double) tonnesforcepercubiccentimeter; - return new SpecificWeight((value*9806650199.60653)); + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); } -#endif /// /// Get SpecificWeight from TonnesForcePerCubicMeter. @@ -524,17 +435,13 @@ public static SpecificWeight FromTonnesForcePerCubicCentimeter(QuantityValue ton #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromTonnesForcePerCubicMeter(double tonnesforcepercubicmeter) - { - double value = (double) tonnesforcepercubicmeter; - return new SpecificWeight(value*9806.65019960653); - } #else public static SpecificWeight FromTonnesForcePerCubicMeter(QuantityValue tonnesforcepercubicmeter) +#endif { double value = (double) tonnesforcepercubicmeter; - return new SpecificWeight((value*9806.65019960653)); + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); } -#endif /// /// Get SpecificWeight from TonnesForcePerCubicMillimeter. @@ -542,17 +449,13 @@ public static SpecificWeight FromTonnesForcePerCubicMeter(QuantityValue tonnesfo #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static SpecificWeight FromTonnesForcePerCubicMillimeter(double tonnesforcepercubicmillimeter) - { - double value = (double) tonnesforcepercubicmillimeter; - return new SpecificWeight(value*9806650199606.53); - } #else public static SpecificWeight FromTonnesForcePerCubicMillimeter(QuantityValue tonnesforcepercubicmillimeter) +#endif { double value = (double) tonnesforcepercubicmillimeter; - return new SpecificWeight((value*9806650199606.53)); + return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMillimeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -812,44 +715,7 @@ public static SpecificWeight From(double value, SpecificWeightUnit fromUnit) public static SpecificWeight From(QuantityValue value, SpecificWeightUnit fromUnit) #endif { - switch (fromUnit) - { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: - return FromKilogramsForcePerCubicCentimeter(value); - case SpecificWeightUnit.KilogramForcePerCubicMeter: - return FromKilogramsForcePerCubicMeter(value); - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: - return FromKilogramsForcePerCubicMillimeter(value); - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: - return FromKilonewtonsPerCubicCentimeter(value); - case SpecificWeightUnit.KilonewtonPerCubicMeter: - return FromKilonewtonsPerCubicMeter(value); - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: - return FromKilonewtonsPerCubicMillimeter(value); - case SpecificWeightUnit.KilopoundForcePerCubicFoot: - return FromKilopoundsForcePerCubicFoot(value); - case SpecificWeightUnit.KilopoundForcePerCubicInch: - return FromKilopoundsForcePerCubicInch(value); - case SpecificWeightUnit.NewtonPerCubicCentimeter: - return FromNewtonsPerCubicCentimeter(value); - case SpecificWeightUnit.NewtonPerCubicMeter: - return FromNewtonsPerCubicMeter(value); - case SpecificWeightUnit.NewtonPerCubicMillimeter: - return FromNewtonsPerCubicMillimeter(value); - case SpecificWeightUnit.PoundForcePerCubicFoot: - return FromPoundsForcePerCubicFoot(value); - case SpecificWeightUnit.PoundForcePerCubicInch: - return FromPoundsForcePerCubicInch(value); - case SpecificWeightUnit.TonneForcePerCubicCentimeter: - return FromTonnesForcePerCubicCentimeter(value); - case SpecificWeightUnit.TonneForcePerCubicMeter: - return FromTonnesForcePerCubicMeter(value); - case SpecificWeightUnit.TonneForcePerCubicMillimeter: - return FromTonnesForcePerCubicMillimeter(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new SpecificWeight((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -866,44 +732,8 @@ public static SpecificWeight From(QuantityValue value, SpecificWeightUnit fromUn { return null; } - switch (fromUnit) - { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: - return FromKilogramsForcePerCubicCentimeter(value.Value); - case SpecificWeightUnit.KilogramForcePerCubicMeter: - return FromKilogramsForcePerCubicMeter(value.Value); - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: - return FromKilogramsForcePerCubicMillimeter(value.Value); - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: - return FromKilonewtonsPerCubicCentimeter(value.Value); - case SpecificWeightUnit.KilonewtonPerCubicMeter: - return FromKilonewtonsPerCubicMeter(value.Value); - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: - return FromKilonewtonsPerCubicMillimeter(value.Value); - case SpecificWeightUnit.KilopoundForcePerCubicFoot: - return FromKilopoundsForcePerCubicFoot(value.Value); - case SpecificWeightUnit.KilopoundForcePerCubicInch: - return FromKilopoundsForcePerCubicInch(value.Value); - case SpecificWeightUnit.NewtonPerCubicCentimeter: - return FromNewtonsPerCubicCentimeter(value.Value); - case SpecificWeightUnit.NewtonPerCubicMeter: - return FromNewtonsPerCubicMeter(value.Value); - case SpecificWeightUnit.NewtonPerCubicMillimeter: - return FromNewtonsPerCubicMillimeter(value.Value); - case SpecificWeightUnit.PoundForcePerCubicFoot: - return FromPoundsForcePerCubicFoot(value.Value); - case SpecificWeightUnit.PoundForcePerCubicInch: - return FromPoundsForcePerCubicInch(value.Value); - case SpecificWeightUnit.TonneForcePerCubicCentimeter: - return FromTonnesForcePerCubicCentimeter(value.Value); - case SpecificWeightUnit.TonneForcePerCubicMeter: - return FromTonnesForcePerCubicMeter(value.Value); - case SpecificWeightUnit.TonneForcePerCubicMillimeter: - return FromTonnesForcePerCubicMillimeter(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new SpecificWeight((double)value.Value, fromUnit); } #endif @@ -922,12 +752,29 @@ public static string GetAbbreviation(SpecificWeightUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(SpecificWeightUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + SpecificWeightUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -938,37 +785,37 @@ public static string GetAbbreviation(SpecificWeightUnit unit, [CanBeNull] Cultur #if !WINDOWS_UWP public static SpecificWeight operator -(SpecificWeight right) { - return new SpecificWeight(-right._newtonsPerCubicMeter); + return new SpecificWeight(-right.Value, right.Unit); } public static SpecificWeight operator +(SpecificWeight left, SpecificWeight right) { - return new SpecificWeight(left._newtonsPerCubicMeter + right._newtonsPerCubicMeter); + return new SpecificWeight(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static SpecificWeight operator -(SpecificWeight left, SpecificWeight right) { - return new SpecificWeight(left._newtonsPerCubicMeter - right._newtonsPerCubicMeter); + return new SpecificWeight(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static SpecificWeight operator *(double left, SpecificWeight right) { - return new SpecificWeight(left*right._newtonsPerCubicMeter); + return new SpecificWeight(left * right.Value, right.Unit); } public static SpecificWeight operator *(SpecificWeight left, double right) { - return new SpecificWeight(left._newtonsPerCubicMeter*(double)right); + return new SpecificWeight(left.Value * right, left.Unit); } public static SpecificWeight operator /(SpecificWeight left, double right) { - return new SpecificWeight(left._newtonsPerCubicMeter/(double)right); + return new SpecificWeight(left.Value / right, left.Unit); } public static double operator /(SpecificWeight left, SpecificWeight right) { - return Convert.ToDouble(left._newtonsPerCubicMeter/right._newtonsPerCubicMeter); + return left.NewtonsPerCubicMeter / right.NewtonsPerCubicMeter; } #endif @@ -991,43 +838,43 @@ public int CompareTo(object obj) #endif int CompareTo(SpecificWeight other) { - return _newtonsPerCubicMeter.CompareTo(other._newtonsPerCubicMeter); + return AsBaseUnitNewtonsPerCubicMeter().CompareTo(other.AsBaseUnitNewtonsPerCubicMeter()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(SpecificWeight left, SpecificWeight right) { - return left._newtonsPerCubicMeter <= right._newtonsPerCubicMeter; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(SpecificWeight left, SpecificWeight right) { - return left._newtonsPerCubicMeter >= right._newtonsPerCubicMeter; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(SpecificWeight left, SpecificWeight right) { - return left._newtonsPerCubicMeter < right._newtonsPerCubicMeter; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(SpecificWeight left, SpecificWeight right) { - return left._newtonsPerCubicMeter > right._newtonsPerCubicMeter; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(SpecificWeight left, SpecificWeight right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtonsPerCubicMeter == right._newtonsPerCubicMeter; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(SpecificWeight left, SpecificWeight right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtonsPerCubicMeter != right._newtonsPerCubicMeter; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1039,7 +886,7 @@ public override bool Equals(object obj) return false; } - return _newtonsPerCubicMeter.Equals(((SpecificWeight) obj)._newtonsPerCubicMeter); + return AsBaseUnitNewtonsPerCubicMeter().Equals(((SpecificWeight) obj).AsBaseUnitNewtonsPerCubicMeter()); } /// @@ -1052,12 +899,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(SpecificWeight other, SpecificWeight maxError) { - return Math.Abs(_newtonsPerCubicMeter - other._newtonsPerCubicMeter) <= maxError._newtonsPerCubicMeter; + return Math.Abs(AsBaseUnitNewtonsPerCubicMeter() - other.AsBaseUnitNewtonsPerCubicMeter()) <= maxError.AsBaseUnitNewtonsPerCubicMeter(); } public override int GetHashCode() { - return _newtonsPerCubicMeter.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1067,44 +914,34 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(SpecificWeightUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitNewtonsPerCubicMeter(); + switch (unit) { - case SpecificWeightUnit.KilogramForcePerCubicCentimeter: - return KilogramsForcePerCubicCentimeter; - case SpecificWeightUnit.KilogramForcePerCubicMeter: - return KilogramsForcePerCubicMeter; - case SpecificWeightUnit.KilogramForcePerCubicMillimeter: - return KilogramsForcePerCubicMillimeter; - case SpecificWeightUnit.KilonewtonPerCubicCentimeter: - return KilonewtonsPerCubicCentimeter; - case SpecificWeightUnit.KilonewtonPerCubicMeter: - return KilonewtonsPerCubicMeter; - case SpecificWeightUnit.KilonewtonPerCubicMillimeter: - return KilonewtonsPerCubicMillimeter; - case SpecificWeightUnit.KilopoundForcePerCubicFoot: - return KilopoundsForcePerCubicFoot; - case SpecificWeightUnit.KilopoundForcePerCubicInch: - return KilopoundsForcePerCubicInch; - case SpecificWeightUnit.NewtonPerCubicCentimeter: - return NewtonsPerCubicCentimeter; - case SpecificWeightUnit.NewtonPerCubicMeter: - return NewtonsPerCubicMeter; - case SpecificWeightUnit.NewtonPerCubicMillimeter: - return NewtonsPerCubicMillimeter; - case SpecificWeightUnit.PoundForcePerCubicFoot: - return PoundsForcePerCubicFoot; - case SpecificWeightUnit.PoundForcePerCubicInch: - return PoundsForcePerCubicInch; - case SpecificWeightUnit.TonneForcePerCubicCentimeter: - return TonnesForcePerCubicCentimeter; - case SpecificWeightUnit.TonneForcePerCubicMeter: - return TonnesForcePerCubicMeter; - case SpecificWeightUnit.TonneForcePerCubicMillimeter: - return TonnesForcePerCubicMillimeter; + case SpecificWeightUnit.KilogramForcePerCubicCentimeter: return baseUnitValue*1.01971619222242E-07; + case SpecificWeightUnit.KilogramForcePerCubicMeter: return baseUnitValue*0.101971619222242; + case SpecificWeightUnit.KilogramForcePerCubicMillimeter: return baseUnitValue*1.01971619222242E-10; + case SpecificWeightUnit.KilonewtonPerCubicCentimeter: return (baseUnitValue*0.000001) / 1e3d; + case SpecificWeightUnit.KilonewtonPerCubicMeter: return (baseUnitValue) / 1e3d; + case SpecificWeightUnit.KilonewtonPerCubicMillimeter: return (baseUnitValue*0.000000001) / 1e3d; + case SpecificWeightUnit.KilopoundForcePerCubicFoot: return (baseUnitValue*0.00636587980366089) / 1e3d; + case SpecificWeightUnit.KilopoundForcePerCubicInch: return (baseUnitValue*3.68395821971116E-06) / 1e3d; + case SpecificWeightUnit.NewtonPerCubicCentimeter: return baseUnitValue*0.000001; + case SpecificWeightUnit.NewtonPerCubicMeter: return baseUnitValue; + case SpecificWeightUnit.NewtonPerCubicMillimeter: return baseUnitValue*0.000000001; + case SpecificWeightUnit.PoundForcePerCubicFoot: return baseUnitValue*0.00636587980366089; + case SpecificWeightUnit.PoundForcePerCubicInch: return baseUnitValue*3.68395821971116E-06; + case SpecificWeightUnit.TonneForcePerCubicCentimeter: return baseUnitValue*1.01971619222242E-10; + case SpecificWeightUnit.TonneForcePerCubicMeter: return baseUnitValue*0.000101971619222242; + case SpecificWeightUnit.TonneForcePerCubicMillimeter: return baseUnitValue*1.01971619222242E-13; default: throw new NotImplementedException("unit: " + unit); @@ -1146,7 +983,11 @@ public static SpecificWeight Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1165,17 +1006,24 @@ public static SpecificWeight Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static SpecificWeight Parse(string str, [CanBeNull] Culture culture) + public static SpecificWeight Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1201,16 +1049,41 @@ public static bool TryParse([CanBeNull] string str, out SpecificWeight result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out SpecificWeight result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out SpecificWeight result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1223,6 +1096,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1236,11 +1110,14 @@ public static SpecificWeightUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static SpecificWeightUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1249,6 +1126,8 @@ public static SpecificWeightUnit ParseUnit(string str, [CanBeNull] string cultur /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1261,18 +1140,18 @@ public static SpecificWeightUnit ParseUnit(string str, [CanBeNull] string cultur #else public #endif - static SpecificWeightUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static SpecificWeightUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == SpecificWeightUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpecificWeightUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1281,6 +1160,7 @@ static SpecificWeightUnit ParseUnit(string str, IFormatProvider formatProvider = #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is NewtonPerCubicMeter /// @@ -1292,7 +1172,7 @@ static SpecificWeightUnit ParseUnit(string str, IFormatProvider formatProvider = /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1309,74 +1189,144 @@ public string ToString(SpecificWeightUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(SpecificWeightUnit unit, [CanBeNull] Culture culture) + public string ToString( + SpecificWeightUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(SpecificWeightUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + SpecificWeightUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(SpecificWeightUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + SpecificWeightUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of SpecificWeight /// - public static SpecificWeight MaxValue - { - get - { - return new SpecificWeight(double.MaxValue); - } - } + public static SpecificWeight MaxValue => new SpecificWeight(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of SpecificWeight /// - public static SpecificWeight MinValue + public static SpecificWeight MinValue => new SpecificWeight(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitNewtonsPerCubicMeter() { - get + if (Unit == SpecificWeightUnit.NewtonPerCubicMeter) { return _value; } + + switch (Unit) { - return new SpecificWeight(double.MinValue); - } - } - } + case SpecificWeightUnit.KilogramForcePerCubicCentimeter: return _value*9806650.19960652; + case SpecificWeightUnit.KilogramForcePerCubicMeter: return _value*9.80665019960652; + case SpecificWeightUnit.KilogramForcePerCubicMillimeter: return _value*9806650199.60653; + case SpecificWeightUnit.KilonewtonPerCubicCentimeter: return (_value*1000000) * 1e3d; + case SpecificWeightUnit.KilonewtonPerCubicMeter: return (_value) * 1e3d; + case SpecificWeightUnit.KilonewtonPerCubicMillimeter: return (_value*1000000000) * 1e3d; + case SpecificWeightUnit.KilopoundForcePerCubicFoot: return (_value*157.087477433193) * 1e3d; + case SpecificWeightUnit.KilopoundForcePerCubicInch: return (_value*271447.161004558) * 1e3d; + case SpecificWeightUnit.NewtonPerCubicCentimeter: return _value*1000000; + case SpecificWeightUnit.NewtonPerCubicMeter: return _value; + case SpecificWeightUnit.NewtonPerCubicMillimeter: return _value*1000000000; + case SpecificWeightUnit.PoundForcePerCubicFoot: return _value*157.087477433193; + case SpecificWeightUnit.PoundForcePerCubicInch: return _value*271447.161004558; + case SpecificWeightUnit.TonneForcePerCubicCentimeter: return _value*9806650199.60653; + case SpecificWeightUnit.TonneForcePerCubicMeter: return _value*9806.65019960653; + case SpecificWeightUnit.TonneForcePerCubicMillimeter: return _value*9806650199606.53; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(SpecificWeightUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs index fd2e9c8562..7b9e30f20a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Speed : IComparable, IComparable #endif { /// - /// Base unit of Speed. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly SpeedUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _metersPerSecond; + public SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Speed() : this(0) + public Speed() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Speed(double meterspersecond) { - _metersPerSecond = Convert.ToDouble(meterspersecond); + _value = Convert.ToDouble(meterspersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Speed(double numericValue, SpeedUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit MeterPerSecond. + /// + /// Value assuming base unit MeterPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Speed(long meterspersecond) - { - _metersPerSecond = Convert.ToDouble(meterspersecond); - } + Speed(long meterspersecond) : this(Convert.ToDouble(meterspersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit MeterPerSecond. + /// + /// Value assuming base unit MeterPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Speed(decimal meterspersecond) - { - _metersPerSecond = Convert.ToDouble(meterspersecond); - } + Speed(decimal meterspersecond) : this(Convert.ToDouble(meterspersecond), BaseUnit) { } #region Properties @@ -119,280 +156,146 @@ public Speed(double meterspersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static SpeedUnit BaseUnit - { - get { return SpeedUnit.MeterPerSecond; } - } + public static SpeedUnit BaseUnit => SpeedUnit.MeterPerSecond; /// /// All units of measurement for the Speed quantity. /// public static SpeedUnit[] Units { get; } = Enum.GetValues(typeof(SpeedUnit)).Cast().ToArray(); - /// /// Get Speed in CentimetersPerHour. /// - public double CentimetersPerHour - { - get { return (_metersPerSecond*3600) / 1e-2d; } - } - + public double CentimetersPerHour => As(SpeedUnit.CentimeterPerHour); /// /// Get Speed in CentimetersPerMinutes. /// - public double CentimetersPerMinutes - { - get { return (_metersPerSecond*60) / 1e-2d; } - } - + public double CentimetersPerMinutes => As(SpeedUnit.CentimeterPerMinute); /// /// Get Speed in CentimetersPerSecond. /// - public double CentimetersPerSecond - { - get { return (_metersPerSecond) / 1e-2d; } - } - + public double CentimetersPerSecond => As(SpeedUnit.CentimeterPerSecond); /// /// Get Speed in DecimetersPerMinutes. /// - public double DecimetersPerMinutes - { - get { return (_metersPerSecond*60) / 1e-1d; } - } - + public double DecimetersPerMinutes => As(SpeedUnit.DecimeterPerMinute); /// /// Get Speed in DecimetersPerSecond. /// - public double DecimetersPerSecond - { - get { return (_metersPerSecond) / 1e-1d; } - } - + public double DecimetersPerSecond => As(SpeedUnit.DecimeterPerSecond); /// /// Get Speed in FeetPerHour. /// - public double FeetPerHour - { - get { return _metersPerSecond/0.3048*3600; } - } - + public double FeetPerHour => As(SpeedUnit.FootPerHour); /// /// Get Speed in FeetPerMinute. /// - public double FeetPerMinute - { - get { return _metersPerSecond/0.3048*60; } - } - + public double FeetPerMinute => As(SpeedUnit.FootPerMinute); /// /// Get Speed in FeetPerSecond. /// - public double FeetPerSecond - { - get { return _metersPerSecond/0.3048; } - } - + public double FeetPerSecond => As(SpeedUnit.FootPerSecond); /// /// Get Speed in InchesPerHour. /// - public double InchesPerHour - { - get { return (_metersPerSecond/2.54e-2)*3600; } - } - + public double InchesPerHour => As(SpeedUnit.InchPerHour); /// /// Get Speed in InchesPerMinute. /// - public double InchesPerMinute - { - get { return (_metersPerSecond/2.54e-2)*60; } - } - + public double InchesPerMinute => As(SpeedUnit.InchPerMinute); /// /// Get Speed in InchesPerSecond. /// - public double InchesPerSecond - { - get { return _metersPerSecond/2.54e-2; } - } - + public double InchesPerSecond => As(SpeedUnit.InchPerSecond); /// /// Get Speed in KilometersPerHour. /// - public double KilometersPerHour - { - get { return (_metersPerSecond*3600) / 1e3d; } - } - + public double KilometersPerHour => As(SpeedUnit.KilometerPerHour); /// /// Get Speed in KilometersPerMinutes. /// - public double KilometersPerMinutes - { - get { return (_metersPerSecond*60) / 1e3d; } - } - + public double KilometersPerMinutes => As(SpeedUnit.KilometerPerMinute); /// /// Get Speed in KilometersPerSecond. /// - public double KilometersPerSecond - { - get { return (_metersPerSecond) / 1e3d; } - } - + public double KilometersPerSecond => As(SpeedUnit.KilometerPerSecond); /// /// Get Speed in Knots. /// - public double Knots - { - get { return _metersPerSecond/0.514444; } - } - + public double Knots => As(SpeedUnit.Knot); /// /// Get Speed in MetersPerHour. /// - public double MetersPerHour - { - get { return _metersPerSecond*3600; } - } - + public double MetersPerHour => As(SpeedUnit.MeterPerHour); /// /// Get Speed in MetersPerMinutes. /// - public double MetersPerMinutes - { - get { return _metersPerSecond*60; } - } - + public double MetersPerMinutes => As(SpeedUnit.MeterPerMinute); /// /// Get Speed in MetersPerSecond. /// - public double MetersPerSecond - { - get { return _metersPerSecond; } - } - + public double MetersPerSecond => As(SpeedUnit.MeterPerSecond); /// /// Get Speed in MicrometersPerMinutes. /// - public double MicrometersPerMinutes - { - get { return (_metersPerSecond*60) / 1e-6d; } - } - + public double MicrometersPerMinutes => As(SpeedUnit.MicrometerPerMinute); /// /// Get Speed in MicrometersPerSecond. /// - public double MicrometersPerSecond - { - get { return (_metersPerSecond) / 1e-6d; } - } - + public double MicrometersPerSecond => As(SpeedUnit.MicrometerPerSecond); /// /// Get Speed in MilesPerHour. /// - public double MilesPerHour - { - get { return _metersPerSecond/0.44704; } - } - + public double MilesPerHour => As(SpeedUnit.MilePerHour); /// /// Get Speed in MillimetersPerHour. /// - public double MillimetersPerHour - { - get { return (_metersPerSecond*3600) / 1e-3d; } - } - + public double MillimetersPerHour => As(SpeedUnit.MillimeterPerHour); /// /// Get Speed in MillimetersPerMinutes. /// - public double MillimetersPerMinutes - { - get { return (_metersPerSecond*60) / 1e-3d; } - } - + public double MillimetersPerMinutes => As(SpeedUnit.MillimeterPerMinute); /// /// Get Speed in MillimetersPerSecond. /// - public double MillimetersPerSecond - { - get { return (_metersPerSecond) / 1e-3d; } - } - + public double MillimetersPerSecond => As(SpeedUnit.MillimeterPerSecond); /// /// Get Speed in NanometersPerMinutes. /// - public double NanometersPerMinutes - { - get { return (_metersPerSecond*60) / 1e-9d; } - } - + public double NanometersPerMinutes => As(SpeedUnit.NanometerPerMinute); /// /// Get Speed in NanometersPerSecond. /// - public double NanometersPerSecond - { - get { return (_metersPerSecond) / 1e-9d; } - } - + public double NanometersPerSecond => As(SpeedUnit.NanometerPerSecond); /// /// Get Speed in UsSurveyFeetPerHour. /// - public double UsSurveyFeetPerHour - { - get { return (_metersPerSecond*3937/1200)*3600; } - } - + public double UsSurveyFeetPerHour => As(SpeedUnit.UsSurveyFootPerHour); /// /// Get Speed in UsSurveyFeetPerMinute. /// - public double UsSurveyFeetPerMinute - { - get { return (_metersPerSecond*3937/1200)*60; } - } - + public double UsSurveyFeetPerMinute => As(SpeedUnit.UsSurveyFootPerMinute); /// /// Get Speed in UsSurveyFeetPerSecond. /// - public double UsSurveyFeetPerSecond - { - get { return _metersPerSecond*3937/1200; } - } - + public double UsSurveyFeetPerSecond => As(SpeedUnit.UsSurveyFootPerSecond); /// /// Get Speed in YardsPerHour. /// - public double YardsPerHour - { - get { return _metersPerSecond/0.9144*3600; } - } - + public double YardsPerHour => As(SpeedUnit.YardPerHour); /// /// Get Speed in YardsPerMinute. /// - public double YardsPerMinute - { - get { return _metersPerSecond/0.9144*60; } - } - + public double YardsPerMinute => As(SpeedUnit.YardPerMinute); /// /// Get Speed in YardsPerSecond. /// - public double YardsPerSecond - { - get { return _metersPerSecond/0.9144; } - } + public double YardsPerSecond => As(SpeedUnit.YardPerSecond); #endregion #region Static - public static Speed Zero - { - get { return new Speed(); } - } + public static Speed Zero => new Speed(0, BaseUnit); /// /// Get Speed from CentimetersPerHour. @@ -400,17 +303,13 @@ public static Speed Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromCentimetersPerHour(double centimetersperhour) - { - double value = (double) centimetersperhour; - return new Speed((value/3600) * 1e-2d); - } #else public static Speed FromCentimetersPerHour(QuantityValue centimetersperhour) +#endif { double value = (double) centimetersperhour; - return new Speed(((value/3600) * 1e-2d)); + return new Speed(value, SpeedUnit.CentimeterPerHour); } -#endif /// /// Get Speed from CentimetersPerMinutes. @@ -418,17 +317,13 @@ public static Speed FromCentimetersPerHour(QuantityValue centimetersperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromCentimetersPerMinutes(double centimetersperminutes) - { - double value = (double) centimetersperminutes; - return new Speed((value/60) * 1e-2d); - } #else public static Speed FromCentimetersPerMinutes(QuantityValue centimetersperminutes) +#endif { double value = (double) centimetersperminutes; - return new Speed(((value/60) * 1e-2d)); + return new Speed(value, SpeedUnit.CentimeterPerMinute); } -#endif /// /// Get Speed from CentimetersPerSecond. @@ -436,17 +331,13 @@ public static Speed FromCentimetersPerMinutes(QuantityValue centimetersperminute #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromCentimetersPerSecond(double centimeterspersecond) - { - double value = (double) centimeterspersecond; - return new Speed((value) * 1e-2d); - } #else public static Speed FromCentimetersPerSecond(QuantityValue centimeterspersecond) +#endif { double value = (double) centimeterspersecond; - return new Speed(((value) * 1e-2d)); + return new Speed(value, SpeedUnit.CentimeterPerSecond); } -#endif /// /// Get Speed from DecimetersPerMinutes. @@ -454,17 +345,13 @@ public static Speed FromCentimetersPerSecond(QuantityValue centimeterspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromDecimetersPerMinutes(double decimetersperminutes) - { - double value = (double) decimetersperminutes; - return new Speed((value/60) * 1e-1d); - } #else public static Speed FromDecimetersPerMinutes(QuantityValue decimetersperminutes) +#endif { double value = (double) decimetersperminutes; - return new Speed(((value/60) * 1e-1d)); + return new Speed(value, SpeedUnit.DecimeterPerMinute); } -#endif /// /// Get Speed from DecimetersPerSecond. @@ -472,17 +359,13 @@ public static Speed FromDecimetersPerMinutes(QuantityValue decimetersperminutes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromDecimetersPerSecond(double decimeterspersecond) - { - double value = (double) decimeterspersecond; - return new Speed((value) * 1e-1d); - } #else public static Speed FromDecimetersPerSecond(QuantityValue decimeterspersecond) +#endif { double value = (double) decimeterspersecond; - return new Speed(((value) * 1e-1d)); + return new Speed(value, SpeedUnit.DecimeterPerSecond); } -#endif /// /// Get Speed from FeetPerHour. @@ -490,17 +373,13 @@ public static Speed FromDecimetersPerSecond(QuantityValue decimeterspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromFeetPerHour(double feetperhour) - { - double value = (double) feetperhour; - return new Speed(value*0.3048/3600); - } #else public static Speed FromFeetPerHour(QuantityValue feetperhour) +#endif { double value = (double) feetperhour; - return new Speed((value*0.3048/3600)); + return new Speed(value, SpeedUnit.FootPerHour); } -#endif /// /// Get Speed from FeetPerMinute. @@ -508,17 +387,13 @@ public static Speed FromFeetPerHour(QuantityValue feetperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromFeetPerMinute(double feetperminute) - { - double value = (double) feetperminute; - return new Speed(value*0.3048/60); - } #else public static Speed FromFeetPerMinute(QuantityValue feetperminute) +#endif { double value = (double) feetperminute; - return new Speed((value*0.3048/60)); + return new Speed(value, SpeedUnit.FootPerMinute); } -#endif /// /// Get Speed from FeetPerSecond. @@ -526,17 +401,13 @@ public static Speed FromFeetPerMinute(QuantityValue feetperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromFeetPerSecond(double feetpersecond) - { - double value = (double) feetpersecond; - return new Speed(value*0.3048); - } #else public static Speed FromFeetPerSecond(QuantityValue feetpersecond) +#endif { double value = (double) feetpersecond; - return new Speed((value*0.3048)); + return new Speed(value, SpeedUnit.FootPerSecond); } -#endif /// /// Get Speed from InchesPerHour. @@ -544,17 +415,13 @@ public static Speed FromFeetPerSecond(QuantityValue feetpersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromInchesPerHour(double inchesperhour) - { - double value = (double) inchesperhour; - return new Speed((value/3600)*2.54e-2); - } #else public static Speed FromInchesPerHour(QuantityValue inchesperhour) +#endif { double value = (double) inchesperhour; - return new Speed(((value/3600)*2.54e-2)); + return new Speed(value, SpeedUnit.InchPerHour); } -#endif /// /// Get Speed from InchesPerMinute. @@ -562,17 +429,13 @@ public static Speed FromInchesPerHour(QuantityValue inchesperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromInchesPerMinute(double inchesperminute) - { - double value = (double) inchesperminute; - return new Speed((value/60)*2.54e-2); - } #else public static Speed FromInchesPerMinute(QuantityValue inchesperminute) +#endif { double value = (double) inchesperminute; - return new Speed(((value/60)*2.54e-2)); + return new Speed(value, SpeedUnit.InchPerMinute); } -#endif /// /// Get Speed from InchesPerSecond. @@ -580,17 +443,13 @@ public static Speed FromInchesPerMinute(QuantityValue inchesperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromInchesPerSecond(double inchespersecond) - { - double value = (double) inchespersecond; - return new Speed(value*2.54e-2); - } #else public static Speed FromInchesPerSecond(QuantityValue inchespersecond) +#endif { double value = (double) inchespersecond; - return new Speed((value*2.54e-2)); + return new Speed(value, SpeedUnit.InchPerSecond); } -#endif /// /// Get Speed from KilometersPerHour. @@ -598,17 +457,13 @@ public static Speed FromInchesPerSecond(QuantityValue inchespersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromKilometersPerHour(double kilometersperhour) - { - double value = (double) kilometersperhour; - return new Speed((value/3600) * 1e3d); - } #else public static Speed FromKilometersPerHour(QuantityValue kilometersperhour) +#endif { double value = (double) kilometersperhour; - return new Speed(((value/3600) * 1e3d)); + return new Speed(value, SpeedUnit.KilometerPerHour); } -#endif /// /// Get Speed from KilometersPerMinutes. @@ -616,17 +471,13 @@ public static Speed FromKilometersPerHour(QuantityValue kilometersperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromKilometersPerMinutes(double kilometersperminutes) - { - double value = (double) kilometersperminutes; - return new Speed((value/60) * 1e3d); - } #else public static Speed FromKilometersPerMinutes(QuantityValue kilometersperminutes) +#endif { double value = (double) kilometersperminutes; - return new Speed(((value/60) * 1e3d)); + return new Speed(value, SpeedUnit.KilometerPerMinute); } -#endif /// /// Get Speed from KilometersPerSecond. @@ -634,17 +485,13 @@ public static Speed FromKilometersPerMinutes(QuantityValue kilometersperminutes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromKilometersPerSecond(double kilometerspersecond) - { - double value = (double) kilometerspersecond; - return new Speed((value) * 1e3d); - } #else public static Speed FromKilometersPerSecond(QuantityValue kilometerspersecond) +#endif { double value = (double) kilometerspersecond; - return new Speed(((value) * 1e3d)); + return new Speed(value, SpeedUnit.KilometerPerSecond); } -#endif /// /// Get Speed from Knots. @@ -652,17 +499,13 @@ public static Speed FromKilometersPerSecond(QuantityValue kilometerspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromKnots(double knots) - { - double value = (double) knots; - return new Speed(value*0.514444); - } #else public static Speed FromKnots(QuantityValue knots) +#endif { double value = (double) knots; - return new Speed((value*0.514444)); + return new Speed(value, SpeedUnit.Knot); } -#endif /// /// Get Speed from MetersPerHour. @@ -670,17 +513,13 @@ public static Speed FromKnots(QuantityValue knots) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromMetersPerHour(double metersperhour) - { - double value = (double) metersperhour; - return new Speed(value/3600); - } #else public static Speed FromMetersPerHour(QuantityValue metersperhour) +#endif { double value = (double) metersperhour; - return new Speed((value/3600)); + return new Speed(value, SpeedUnit.MeterPerHour); } -#endif /// /// Get Speed from MetersPerMinutes. @@ -688,17 +527,13 @@ public static Speed FromMetersPerHour(QuantityValue metersperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromMetersPerMinutes(double metersperminutes) - { - double value = (double) metersperminutes; - return new Speed(value/60); - } #else public static Speed FromMetersPerMinutes(QuantityValue metersperminutes) +#endif { double value = (double) metersperminutes; - return new Speed((value/60)); + return new Speed(value, SpeedUnit.MeterPerMinute); } -#endif /// /// Get Speed from MetersPerSecond. @@ -706,17 +541,13 @@ public static Speed FromMetersPerMinutes(QuantityValue metersperminutes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromMetersPerSecond(double meterspersecond) - { - double value = (double) meterspersecond; - return new Speed(value); - } #else public static Speed FromMetersPerSecond(QuantityValue meterspersecond) +#endif { double value = (double) meterspersecond; - return new Speed((value)); + return new Speed(value, SpeedUnit.MeterPerSecond); } -#endif /// /// Get Speed from MicrometersPerMinutes. @@ -724,17 +555,13 @@ public static Speed FromMetersPerSecond(QuantityValue meterspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromMicrometersPerMinutes(double micrometersperminutes) - { - double value = (double) micrometersperminutes; - return new Speed((value/60) * 1e-6d); - } #else public static Speed FromMicrometersPerMinutes(QuantityValue micrometersperminutes) +#endif { double value = (double) micrometersperminutes; - return new Speed(((value/60) * 1e-6d)); + return new Speed(value, SpeedUnit.MicrometerPerMinute); } -#endif /// /// Get Speed from MicrometersPerSecond. @@ -742,17 +569,13 @@ public static Speed FromMicrometersPerMinutes(QuantityValue micrometersperminute #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromMicrometersPerSecond(double micrometerspersecond) - { - double value = (double) micrometerspersecond; - return new Speed((value) * 1e-6d); - } #else public static Speed FromMicrometersPerSecond(QuantityValue micrometerspersecond) +#endif { double value = (double) micrometerspersecond; - return new Speed(((value) * 1e-6d)); + return new Speed(value, SpeedUnit.MicrometerPerSecond); } -#endif /// /// Get Speed from MilesPerHour. @@ -760,17 +583,13 @@ public static Speed FromMicrometersPerSecond(QuantityValue micrometerspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromMilesPerHour(double milesperhour) - { - double value = (double) milesperhour; - return new Speed(value*0.44704); - } #else public static Speed FromMilesPerHour(QuantityValue milesperhour) +#endif { double value = (double) milesperhour; - return new Speed((value*0.44704)); + return new Speed(value, SpeedUnit.MilePerHour); } -#endif /// /// Get Speed from MillimetersPerHour. @@ -778,17 +597,13 @@ public static Speed FromMilesPerHour(QuantityValue milesperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromMillimetersPerHour(double millimetersperhour) - { - double value = (double) millimetersperhour; - return new Speed((value/3600) * 1e-3d); - } #else public static Speed FromMillimetersPerHour(QuantityValue millimetersperhour) +#endif { double value = (double) millimetersperhour; - return new Speed(((value/3600) * 1e-3d)); + return new Speed(value, SpeedUnit.MillimeterPerHour); } -#endif /// /// Get Speed from MillimetersPerMinutes. @@ -796,17 +611,13 @@ public static Speed FromMillimetersPerHour(QuantityValue millimetersperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromMillimetersPerMinutes(double millimetersperminutes) - { - double value = (double) millimetersperminutes; - return new Speed((value/60) * 1e-3d); - } #else public static Speed FromMillimetersPerMinutes(QuantityValue millimetersperminutes) +#endif { double value = (double) millimetersperminutes; - return new Speed(((value/60) * 1e-3d)); + return new Speed(value, SpeedUnit.MillimeterPerMinute); } -#endif /// /// Get Speed from MillimetersPerSecond. @@ -814,17 +625,13 @@ public static Speed FromMillimetersPerMinutes(QuantityValue millimetersperminute #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromMillimetersPerSecond(double millimeterspersecond) - { - double value = (double) millimeterspersecond; - return new Speed((value) * 1e-3d); - } #else public static Speed FromMillimetersPerSecond(QuantityValue millimeterspersecond) +#endif { double value = (double) millimeterspersecond; - return new Speed(((value) * 1e-3d)); + return new Speed(value, SpeedUnit.MillimeterPerSecond); } -#endif /// /// Get Speed from NanometersPerMinutes. @@ -832,17 +639,13 @@ public static Speed FromMillimetersPerSecond(QuantityValue millimeterspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromNanometersPerMinutes(double nanometersperminutes) - { - double value = (double) nanometersperminutes; - return new Speed((value/60) * 1e-9d); - } #else public static Speed FromNanometersPerMinutes(QuantityValue nanometersperminutes) +#endif { double value = (double) nanometersperminutes; - return new Speed(((value/60) * 1e-9d)); + return new Speed(value, SpeedUnit.NanometerPerMinute); } -#endif /// /// Get Speed from NanometersPerSecond. @@ -850,17 +653,13 @@ public static Speed FromNanometersPerMinutes(QuantityValue nanometersperminutes) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromNanometersPerSecond(double nanometerspersecond) - { - double value = (double) nanometerspersecond; - return new Speed((value) * 1e-9d); - } #else public static Speed FromNanometersPerSecond(QuantityValue nanometerspersecond) +#endif { double value = (double) nanometerspersecond; - return new Speed(((value) * 1e-9d)); + return new Speed(value, SpeedUnit.NanometerPerSecond); } -#endif /// /// Get Speed from UsSurveyFeetPerHour. @@ -868,17 +667,13 @@ public static Speed FromNanometersPerSecond(QuantityValue nanometerspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromUsSurveyFeetPerHour(double ussurveyfeetperhour) - { - double value = (double) ussurveyfeetperhour; - return new Speed((value*1200/3937)/3600); - } #else public static Speed FromUsSurveyFeetPerHour(QuantityValue ussurveyfeetperhour) +#endif { double value = (double) ussurveyfeetperhour; - return new Speed(((value*1200/3937)/3600)); + return new Speed(value, SpeedUnit.UsSurveyFootPerHour); } -#endif /// /// Get Speed from UsSurveyFeetPerMinute. @@ -886,17 +681,13 @@ public static Speed FromUsSurveyFeetPerHour(QuantityValue ussurveyfeetperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromUsSurveyFeetPerMinute(double ussurveyfeetperminute) - { - double value = (double) ussurveyfeetperminute; - return new Speed((value*1200/3937)/60); - } #else public static Speed FromUsSurveyFeetPerMinute(QuantityValue ussurveyfeetperminute) +#endif { double value = (double) ussurveyfeetperminute; - return new Speed(((value*1200/3937)/60)); + return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); } -#endif /// /// Get Speed from UsSurveyFeetPerSecond. @@ -904,17 +695,13 @@ public static Speed FromUsSurveyFeetPerMinute(QuantityValue ussurveyfeetperminut #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromUsSurveyFeetPerSecond(double ussurveyfeetpersecond) - { - double value = (double) ussurveyfeetpersecond; - return new Speed(value*1200/3937); - } #else public static Speed FromUsSurveyFeetPerSecond(QuantityValue ussurveyfeetpersecond) +#endif { double value = (double) ussurveyfeetpersecond; - return new Speed((value*1200/3937)); + return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); } -#endif /// /// Get Speed from YardsPerHour. @@ -922,17 +709,13 @@ public static Speed FromUsSurveyFeetPerSecond(QuantityValue ussurveyfeetpersecon #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromYardsPerHour(double yardsperhour) - { - double value = (double) yardsperhour; - return new Speed(value*0.9144/3600); - } #else public static Speed FromYardsPerHour(QuantityValue yardsperhour) +#endif { double value = (double) yardsperhour; - return new Speed((value*0.9144/3600)); + return new Speed(value, SpeedUnit.YardPerHour); } -#endif /// /// Get Speed from YardsPerMinute. @@ -940,17 +723,13 @@ public static Speed FromYardsPerHour(QuantityValue yardsperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromYardsPerMinute(double yardsperminute) - { - double value = (double) yardsperminute; - return new Speed(value*0.9144/60); - } #else public static Speed FromYardsPerMinute(QuantityValue yardsperminute) +#endif { double value = (double) yardsperminute; - return new Speed((value*0.9144/60)); + return new Speed(value, SpeedUnit.YardPerMinute); } -#endif /// /// Get Speed from YardsPerSecond. @@ -958,17 +737,13 @@ public static Speed FromYardsPerMinute(QuantityValue yardsperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Speed FromYardsPerSecond(double yardspersecond) - { - double value = (double) yardspersecond; - return new Speed(value*0.9144); - } #else public static Speed FromYardsPerSecond(QuantityValue yardspersecond) +#endif { double value = (double) yardspersecond; - return new Speed((value*0.9144)); + return new Speed(value, SpeedUnit.YardPerSecond); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1468,76 +1243,7 @@ public static Speed From(double value, SpeedUnit fromUnit) public static Speed From(QuantityValue value, SpeedUnit fromUnit) #endif { - switch (fromUnit) - { - case SpeedUnit.CentimeterPerHour: - return FromCentimetersPerHour(value); - case SpeedUnit.CentimeterPerMinute: - return FromCentimetersPerMinutes(value); - case SpeedUnit.CentimeterPerSecond: - return FromCentimetersPerSecond(value); - case SpeedUnit.DecimeterPerMinute: - return FromDecimetersPerMinutes(value); - case SpeedUnit.DecimeterPerSecond: - return FromDecimetersPerSecond(value); - case SpeedUnit.FootPerHour: - return FromFeetPerHour(value); - case SpeedUnit.FootPerMinute: - return FromFeetPerMinute(value); - case SpeedUnit.FootPerSecond: - return FromFeetPerSecond(value); - case SpeedUnit.InchPerHour: - return FromInchesPerHour(value); - case SpeedUnit.InchPerMinute: - return FromInchesPerMinute(value); - case SpeedUnit.InchPerSecond: - return FromInchesPerSecond(value); - case SpeedUnit.KilometerPerHour: - return FromKilometersPerHour(value); - case SpeedUnit.KilometerPerMinute: - return FromKilometersPerMinutes(value); - case SpeedUnit.KilometerPerSecond: - return FromKilometersPerSecond(value); - case SpeedUnit.Knot: - return FromKnots(value); - case SpeedUnit.MeterPerHour: - return FromMetersPerHour(value); - case SpeedUnit.MeterPerMinute: - return FromMetersPerMinutes(value); - case SpeedUnit.MeterPerSecond: - return FromMetersPerSecond(value); - case SpeedUnit.MicrometerPerMinute: - return FromMicrometersPerMinutes(value); - case SpeedUnit.MicrometerPerSecond: - return FromMicrometersPerSecond(value); - case SpeedUnit.MilePerHour: - return FromMilesPerHour(value); - case SpeedUnit.MillimeterPerHour: - return FromMillimetersPerHour(value); - case SpeedUnit.MillimeterPerMinute: - return FromMillimetersPerMinutes(value); - case SpeedUnit.MillimeterPerSecond: - return FromMillimetersPerSecond(value); - case SpeedUnit.NanometerPerMinute: - return FromNanometersPerMinutes(value); - case SpeedUnit.NanometerPerSecond: - return FromNanometersPerSecond(value); - case SpeedUnit.UsSurveyFootPerHour: - return FromUsSurveyFeetPerHour(value); - case SpeedUnit.UsSurveyFootPerMinute: - return FromUsSurveyFeetPerMinute(value); - case SpeedUnit.UsSurveyFootPerSecond: - return FromUsSurveyFeetPerSecond(value); - case SpeedUnit.YardPerHour: - return FromYardsPerHour(value); - case SpeedUnit.YardPerMinute: - return FromYardsPerMinute(value); - case SpeedUnit.YardPerSecond: - return FromYardsPerSecond(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Speed((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1554,76 +1260,8 @@ public static Speed From(QuantityValue value, SpeedUnit fromUnit) { return null; } - switch (fromUnit) - { - case SpeedUnit.CentimeterPerHour: - return FromCentimetersPerHour(value.Value); - case SpeedUnit.CentimeterPerMinute: - return FromCentimetersPerMinutes(value.Value); - case SpeedUnit.CentimeterPerSecond: - return FromCentimetersPerSecond(value.Value); - case SpeedUnit.DecimeterPerMinute: - return FromDecimetersPerMinutes(value.Value); - case SpeedUnit.DecimeterPerSecond: - return FromDecimetersPerSecond(value.Value); - case SpeedUnit.FootPerHour: - return FromFeetPerHour(value.Value); - case SpeedUnit.FootPerMinute: - return FromFeetPerMinute(value.Value); - case SpeedUnit.FootPerSecond: - return FromFeetPerSecond(value.Value); - case SpeedUnit.InchPerHour: - return FromInchesPerHour(value.Value); - case SpeedUnit.InchPerMinute: - return FromInchesPerMinute(value.Value); - case SpeedUnit.InchPerSecond: - return FromInchesPerSecond(value.Value); - case SpeedUnit.KilometerPerHour: - return FromKilometersPerHour(value.Value); - case SpeedUnit.KilometerPerMinute: - return FromKilometersPerMinutes(value.Value); - case SpeedUnit.KilometerPerSecond: - return FromKilometersPerSecond(value.Value); - case SpeedUnit.Knot: - return FromKnots(value.Value); - case SpeedUnit.MeterPerHour: - return FromMetersPerHour(value.Value); - case SpeedUnit.MeterPerMinute: - return FromMetersPerMinutes(value.Value); - case SpeedUnit.MeterPerSecond: - return FromMetersPerSecond(value.Value); - case SpeedUnit.MicrometerPerMinute: - return FromMicrometersPerMinutes(value.Value); - case SpeedUnit.MicrometerPerSecond: - return FromMicrometersPerSecond(value.Value); - case SpeedUnit.MilePerHour: - return FromMilesPerHour(value.Value); - case SpeedUnit.MillimeterPerHour: - return FromMillimetersPerHour(value.Value); - case SpeedUnit.MillimeterPerMinute: - return FromMillimetersPerMinutes(value.Value); - case SpeedUnit.MillimeterPerSecond: - return FromMillimetersPerSecond(value.Value); - case SpeedUnit.NanometerPerMinute: - return FromNanometersPerMinutes(value.Value); - case SpeedUnit.NanometerPerSecond: - return FromNanometersPerSecond(value.Value); - case SpeedUnit.UsSurveyFootPerHour: - return FromUsSurveyFeetPerHour(value.Value); - case SpeedUnit.UsSurveyFootPerMinute: - return FromUsSurveyFeetPerMinute(value.Value); - case SpeedUnit.UsSurveyFootPerSecond: - return FromUsSurveyFeetPerSecond(value.Value); - case SpeedUnit.YardPerHour: - return FromYardsPerHour(value.Value); - case SpeedUnit.YardPerMinute: - return FromYardsPerMinute(value.Value); - case SpeedUnit.YardPerSecond: - return FromYardsPerSecond(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Speed((double)value.Value, fromUnit); } #endif @@ -1642,12 +1280,29 @@ public static string GetAbbreviation(SpeedUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(SpeedUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + SpeedUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1658,37 +1313,37 @@ public static string GetAbbreviation(SpeedUnit unit, [CanBeNull] Culture culture #if !WINDOWS_UWP public static Speed operator -(Speed right) { - return new Speed(-right._metersPerSecond); + return new Speed(-right.Value, right.Unit); } public static Speed operator +(Speed left, Speed right) { - return new Speed(left._metersPerSecond + right._metersPerSecond); + return new Speed(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Speed operator -(Speed left, Speed right) { - return new Speed(left._metersPerSecond - right._metersPerSecond); + return new Speed(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Speed operator *(double left, Speed right) { - return new Speed(left*right._metersPerSecond); + return new Speed(left * right.Value, right.Unit); } public static Speed operator *(Speed left, double right) { - return new Speed(left._metersPerSecond*(double)right); + return new Speed(left.Value * right, left.Unit); } public static Speed operator /(Speed left, double right) { - return new Speed(left._metersPerSecond/(double)right); + return new Speed(left.Value / right, left.Unit); } public static double operator /(Speed left, Speed right) { - return Convert.ToDouble(left._metersPerSecond/right._metersPerSecond); + return left.MetersPerSecond / right.MetersPerSecond; } #endif @@ -1711,43 +1366,43 @@ public int CompareTo(object obj) #endif int CompareTo(Speed other) { - return _metersPerSecond.CompareTo(other._metersPerSecond); + return AsBaseUnitMetersPerSecond().CompareTo(other.AsBaseUnitMetersPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Speed left, Speed right) { - return left._metersPerSecond <= right._metersPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Speed left, Speed right) { - return left._metersPerSecond >= right._metersPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Speed left, Speed right) { - return left._metersPerSecond < right._metersPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Speed left, Speed right) { - return left._metersPerSecond > right._metersPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Speed left, Speed right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._metersPerSecond == right._metersPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Speed left, Speed right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._metersPerSecond != right._metersPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1759,7 +1414,7 @@ public override bool Equals(object obj) return false; } - return _metersPerSecond.Equals(((Speed) obj)._metersPerSecond); + return AsBaseUnitMetersPerSecond().Equals(((Speed) obj).AsBaseUnitMetersPerSecond()); } /// @@ -1772,12 +1427,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Speed other, Speed maxError) { - return Math.Abs(_metersPerSecond - other._metersPerSecond) <= maxError._metersPerSecond; + return Math.Abs(AsBaseUnitMetersPerSecond() - other.AsBaseUnitMetersPerSecond()) <= maxError.AsBaseUnitMetersPerSecond(); } public override int GetHashCode() { - return _metersPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1787,76 +1442,50 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(SpeedUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitMetersPerSecond(); + switch (unit) { - case SpeedUnit.CentimeterPerHour: - return CentimetersPerHour; - case SpeedUnit.CentimeterPerMinute: - return CentimetersPerMinutes; - case SpeedUnit.CentimeterPerSecond: - return CentimetersPerSecond; - case SpeedUnit.DecimeterPerMinute: - return DecimetersPerMinutes; - case SpeedUnit.DecimeterPerSecond: - return DecimetersPerSecond; - case SpeedUnit.FootPerHour: - return FeetPerHour; - case SpeedUnit.FootPerMinute: - return FeetPerMinute; - case SpeedUnit.FootPerSecond: - return FeetPerSecond; - case SpeedUnit.InchPerHour: - return InchesPerHour; - case SpeedUnit.InchPerMinute: - return InchesPerMinute; - case SpeedUnit.InchPerSecond: - return InchesPerSecond; - case SpeedUnit.KilometerPerHour: - return KilometersPerHour; - case SpeedUnit.KilometerPerMinute: - return KilometersPerMinutes; - case SpeedUnit.KilometerPerSecond: - return KilometersPerSecond; - case SpeedUnit.Knot: - return Knots; - case SpeedUnit.MeterPerHour: - return MetersPerHour; - case SpeedUnit.MeterPerMinute: - return MetersPerMinutes; - case SpeedUnit.MeterPerSecond: - return MetersPerSecond; - case SpeedUnit.MicrometerPerMinute: - return MicrometersPerMinutes; - case SpeedUnit.MicrometerPerSecond: - return MicrometersPerSecond; - case SpeedUnit.MilePerHour: - return MilesPerHour; - case SpeedUnit.MillimeterPerHour: - return MillimetersPerHour; - case SpeedUnit.MillimeterPerMinute: - return MillimetersPerMinutes; - case SpeedUnit.MillimeterPerSecond: - return MillimetersPerSecond; - case SpeedUnit.NanometerPerMinute: - return NanometersPerMinutes; - case SpeedUnit.NanometerPerSecond: - return NanometersPerSecond; - case SpeedUnit.UsSurveyFootPerHour: - return UsSurveyFeetPerHour; - case SpeedUnit.UsSurveyFootPerMinute: - return UsSurveyFeetPerMinute; - case SpeedUnit.UsSurveyFootPerSecond: - return UsSurveyFeetPerSecond; - case SpeedUnit.YardPerHour: - return YardsPerHour; - case SpeedUnit.YardPerMinute: - return YardsPerMinute; - case SpeedUnit.YardPerSecond: - return YardsPerSecond; + case SpeedUnit.CentimeterPerHour: return (baseUnitValue*3600) / 1e-2d; + case SpeedUnit.CentimeterPerMinute: return (baseUnitValue*60) / 1e-2d; + case SpeedUnit.CentimeterPerSecond: return (baseUnitValue) / 1e-2d; + case SpeedUnit.DecimeterPerMinute: return (baseUnitValue*60) / 1e-1d; + case SpeedUnit.DecimeterPerSecond: return (baseUnitValue) / 1e-1d; + case SpeedUnit.FootPerHour: return baseUnitValue/0.3048*3600; + case SpeedUnit.FootPerMinute: return baseUnitValue/0.3048*60; + case SpeedUnit.FootPerSecond: return baseUnitValue/0.3048; + case SpeedUnit.InchPerHour: return (baseUnitValue/2.54e-2)*3600; + case SpeedUnit.InchPerMinute: return (baseUnitValue/2.54e-2)*60; + case SpeedUnit.InchPerSecond: return baseUnitValue/2.54e-2; + case SpeedUnit.KilometerPerHour: return (baseUnitValue*3600) / 1e3d; + case SpeedUnit.KilometerPerMinute: return (baseUnitValue*60) / 1e3d; + case SpeedUnit.KilometerPerSecond: return (baseUnitValue) / 1e3d; + case SpeedUnit.Knot: return baseUnitValue/0.514444; + case SpeedUnit.MeterPerHour: return baseUnitValue*3600; + case SpeedUnit.MeterPerMinute: return baseUnitValue*60; + case SpeedUnit.MeterPerSecond: return baseUnitValue; + case SpeedUnit.MicrometerPerMinute: return (baseUnitValue*60) / 1e-6d; + case SpeedUnit.MicrometerPerSecond: return (baseUnitValue) / 1e-6d; + case SpeedUnit.MilePerHour: return baseUnitValue/0.44704; + case SpeedUnit.MillimeterPerHour: return (baseUnitValue*3600) / 1e-3d; + case SpeedUnit.MillimeterPerMinute: return (baseUnitValue*60) / 1e-3d; + case SpeedUnit.MillimeterPerSecond: return (baseUnitValue) / 1e-3d; + case SpeedUnit.NanometerPerMinute: return (baseUnitValue*60) / 1e-9d; + case SpeedUnit.NanometerPerSecond: return (baseUnitValue) / 1e-9d; + case SpeedUnit.UsSurveyFootPerHour: return (baseUnitValue*3937/1200)*3600; + case SpeedUnit.UsSurveyFootPerMinute: return (baseUnitValue*3937/1200)*60; + case SpeedUnit.UsSurveyFootPerSecond: return baseUnitValue*3937/1200; + case SpeedUnit.YardPerHour: return baseUnitValue/0.9144*3600; + case SpeedUnit.YardPerMinute: return baseUnitValue/0.9144*60; + case SpeedUnit.YardPerSecond: return baseUnitValue/0.9144; default: throw new NotImplementedException("unit: " + unit); @@ -1898,7 +1527,11 @@ public static Speed Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1917,17 +1550,24 @@ public static Speed Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Speed Parse(string str, [CanBeNull] Culture culture) + public static Speed Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1953,16 +1593,41 @@ public static bool TryParse([CanBeNull] string str, out Speed result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Speed result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Speed result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1975,6 +1640,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1988,11 +1654,14 @@ public static SpeedUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static SpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -2001,6 +1670,8 @@ public static SpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -2013,18 +1684,18 @@ public static SpeedUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static SpeedUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static SpeedUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == SpeedUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized SpeedUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -2033,6 +1704,7 @@ static SpeedUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is MeterPerSecond /// @@ -2044,7 +1716,7 @@ static SpeedUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -2061,74 +1733,160 @@ public string ToString(SpeedUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(SpeedUnit unit, [CanBeNull] Culture culture) + public string ToString( + SpeedUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(SpeedUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + SpeedUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(SpeedUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + SpeedUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Speed /// - public static Speed MaxValue - { - get - { - return new Speed(double.MaxValue); - } - } + public static Speed MaxValue => new Speed(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Speed /// - public static Speed MinValue - { - get - { - return new Speed(double.MinValue); - } - } - } + public static Speed MinValue => new Speed(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitMetersPerSecond() + { + if (Unit == SpeedUnit.MeterPerSecond) { return _value; } + + switch (Unit) + { + case SpeedUnit.CentimeterPerHour: return (_value/3600) * 1e-2d; + case SpeedUnit.CentimeterPerMinute: return (_value/60) * 1e-2d; + case SpeedUnit.CentimeterPerSecond: return (_value) * 1e-2d; + case SpeedUnit.DecimeterPerMinute: return (_value/60) * 1e-1d; + case SpeedUnit.DecimeterPerSecond: return (_value) * 1e-1d; + case SpeedUnit.FootPerHour: return _value*0.3048/3600; + case SpeedUnit.FootPerMinute: return _value*0.3048/60; + case SpeedUnit.FootPerSecond: return _value*0.3048; + case SpeedUnit.InchPerHour: return (_value/3600)*2.54e-2; + case SpeedUnit.InchPerMinute: return (_value/60)*2.54e-2; + case SpeedUnit.InchPerSecond: return _value*2.54e-2; + case SpeedUnit.KilometerPerHour: return (_value/3600) * 1e3d; + case SpeedUnit.KilometerPerMinute: return (_value/60) * 1e3d; + case SpeedUnit.KilometerPerSecond: return (_value) * 1e3d; + case SpeedUnit.Knot: return _value*0.514444; + case SpeedUnit.MeterPerHour: return _value/3600; + case SpeedUnit.MeterPerMinute: return _value/60; + case SpeedUnit.MeterPerSecond: return _value; + case SpeedUnit.MicrometerPerMinute: return (_value/60) * 1e-6d; + case SpeedUnit.MicrometerPerSecond: return (_value) * 1e-6d; + case SpeedUnit.MilePerHour: return _value*0.44704; + case SpeedUnit.MillimeterPerHour: return (_value/3600) * 1e-3d; + case SpeedUnit.MillimeterPerMinute: return (_value/60) * 1e-3d; + case SpeedUnit.MillimeterPerSecond: return (_value) * 1e-3d; + case SpeedUnit.NanometerPerMinute: return (_value/60) * 1e-9d; + case SpeedUnit.NanometerPerSecond: return (_value) * 1e-9d; + case SpeedUnit.UsSurveyFootPerHour: return (_value*1200/3937)/3600; + case SpeedUnit.UsSurveyFootPerMinute: return (_value*1200/3937)/60; + case SpeedUnit.UsSurveyFootPerSecond: return _value*1200/3937; + case SpeedUnit.YardPerHour: return _value*0.9144/3600; + case SpeedUnit.YardPerMinute: return _value*0.9144/60; + case SpeedUnit.YardPerSecond: return _value*0.9144; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(SpeedUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs index 3dbde27806..14e7e642ef 100644 --- a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Temperature : IComparable, IComparable #endif { /// - /// Base unit of Temperature. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _kelvins; + private readonly TemperatureUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Temperature() : this(0) + public Temperature() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Temperature(double kelvins) { - _kelvins = Convert.ToDouble(kelvins); + _value = Convert.ToDouble(kelvins); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Temperature(double numericValue, TemperatureUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Kelvin. + /// + /// Value assuming base unit Kelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Temperature(long kelvins) - { - _kelvins = Convert.ToDouble(kelvins); - } + Temperature(long kelvins) : this(Convert.ToDouble(kelvins), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Kelvin. + /// + /// Value assuming base unit Kelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Temperature(decimal kelvins) - { - _kelvins = Convert.ToDouble(kelvins); - } + Temperature(decimal kelvins) : this(Convert.ToDouble(kelvins), BaseUnit) { } #region Properties @@ -119,88 +156,50 @@ public Temperature(double kelvins) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static TemperatureUnit BaseUnit - { - get { return TemperatureUnit.Kelvin; } - } + public static TemperatureUnit BaseUnit => TemperatureUnit.Kelvin; /// /// All units of measurement for the Temperature quantity. /// public static TemperatureUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureUnit)).Cast().ToArray(); - /// /// Get Temperature in DegreesCelsius. /// - public double DegreesCelsius - { - get { return _kelvins - 273.15; } - } - + public double DegreesCelsius => As(TemperatureUnit.DegreeCelsius); /// /// Get Temperature in DegreesDelisle. /// - public double DegreesDelisle - { - get { return (_kelvins - 373.15)*-3/2; } - } - + public double DegreesDelisle => As(TemperatureUnit.DegreeDelisle); /// /// Get Temperature in DegreesFahrenheit. /// - public double DegreesFahrenheit - { - get { return (_kelvins - 459.67*5/9)*9/5; } - } - + public double DegreesFahrenheit => As(TemperatureUnit.DegreeFahrenheit); /// /// Get Temperature in DegreesNewton. /// - public double DegreesNewton - { - get { return (_kelvins - 273.15)*33/100; } - } - + public double DegreesNewton => As(TemperatureUnit.DegreeNewton); /// /// Get Temperature in DegreesRankine. /// - public double DegreesRankine - { - get { return _kelvins*9/5; } - } - + public double DegreesRankine => As(TemperatureUnit.DegreeRankine); /// /// Get Temperature in DegreesReaumur. /// - public double DegreesReaumur - { - get { return (_kelvins - 273.15)*4/5; } - } - + public double DegreesReaumur => As(TemperatureUnit.DegreeReaumur); /// /// Get Temperature in DegreesRoemer. /// - public double DegreesRoemer - { - get { return (_kelvins - (273.15 - 7.5*40d/21))*21/40; } - } - + public double DegreesRoemer => As(TemperatureUnit.DegreeRoemer); /// /// Get Temperature in Kelvins. /// - public double Kelvins - { - get { return _kelvins; } - } + public double Kelvins => As(TemperatureUnit.Kelvin); #endregion #region Static - public static Temperature Zero - { - get { return new Temperature(); } - } + public static Temperature Zero => new Temperature(0, BaseUnit); /// /// Get Temperature from DegreesCelsius. @@ -208,17 +207,13 @@ public static Temperature Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Temperature FromDegreesCelsius(double degreescelsius) - { - double value = (double) degreescelsius; - return new Temperature(value + 273.15); - } #else public static Temperature FromDegreesCelsius(QuantityValue degreescelsius) +#endif { double value = (double) degreescelsius; - return new Temperature((value + 273.15)); + return new Temperature(value, TemperatureUnit.DegreeCelsius); } -#endif /// /// Get Temperature from DegreesDelisle. @@ -226,17 +221,13 @@ public static Temperature FromDegreesCelsius(QuantityValue degreescelsius) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Temperature FromDegreesDelisle(double degreesdelisle) - { - double value = (double) degreesdelisle; - return new Temperature(value*-2/3 + 373.15); - } #else public static Temperature FromDegreesDelisle(QuantityValue degreesdelisle) +#endif { double value = (double) degreesdelisle; - return new Temperature((value*-2/3 + 373.15)); + return new Temperature(value, TemperatureUnit.DegreeDelisle); } -#endif /// /// Get Temperature from DegreesFahrenheit. @@ -244,17 +235,13 @@ public static Temperature FromDegreesDelisle(QuantityValue degreesdelisle) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Temperature FromDegreesFahrenheit(double degreesfahrenheit) - { - double value = (double) degreesfahrenheit; - return new Temperature(value*5/9 + 459.67*5/9); - } #else public static Temperature FromDegreesFahrenheit(QuantityValue degreesfahrenheit) +#endif { double value = (double) degreesfahrenheit; - return new Temperature((value*5/9 + 459.67*5/9)); + return new Temperature(value, TemperatureUnit.DegreeFahrenheit); } -#endif /// /// Get Temperature from DegreesNewton. @@ -262,17 +249,13 @@ public static Temperature FromDegreesFahrenheit(QuantityValue degreesfahrenheit) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Temperature FromDegreesNewton(double degreesnewton) - { - double value = (double) degreesnewton; - return new Temperature(value*100/33 + 273.15); - } #else public static Temperature FromDegreesNewton(QuantityValue degreesnewton) +#endif { double value = (double) degreesnewton; - return new Temperature((value*100/33 + 273.15)); + return new Temperature(value, TemperatureUnit.DegreeNewton); } -#endif /// /// Get Temperature from DegreesRankine. @@ -280,17 +263,13 @@ public static Temperature FromDegreesNewton(QuantityValue degreesnewton) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Temperature FromDegreesRankine(double degreesrankine) - { - double value = (double) degreesrankine; - return new Temperature(value*5/9); - } #else public static Temperature FromDegreesRankine(QuantityValue degreesrankine) +#endif { double value = (double) degreesrankine; - return new Temperature((value*5/9)); + return new Temperature(value, TemperatureUnit.DegreeRankine); } -#endif /// /// Get Temperature from DegreesReaumur. @@ -298,17 +277,13 @@ public static Temperature FromDegreesRankine(QuantityValue degreesrankine) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Temperature FromDegreesReaumur(double degreesreaumur) - { - double value = (double) degreesreaumur; - return new Temperature(value*5/4 + 273.15); - } #else public static Temperature FromDegreesReaumur(QuantityValue degreesreaumur) +#endif { double value = (double) degreesreaumur; - return new Temperature((value*5/4 + 273.15)); + return new Temperature(value, TemperatureUnit.DegreeReaumur); } -#endif /// /// Get Temperature from DegreesRoemer. @@ -316,17 +291,13 @@ public static Temperature FromDegreesReaumur(QuantityValue degreesreaumur) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Temperature FromDegreesRoemer(double degreesroemer) - { - double value = (double) degreesroemer; - return new Temperature(value*40/21 + 273.15 - 7.5*40d/21); - } #else public static Temperature FromDegreesRoemer(QuantityValue degreesroemer) +#endif { double value = (double) degreesroemer; - return new Temperature((value*40/21 + 273.15 - 7.5*40d/21)); + return new Temperature(value, TemperatureUnit.DegreeRoemer); } -#endif /// /// Get Temperature from Kelvins. @@ -334,17 +305,13 @@ public static Temperature FromDegreesRoemer(QuantityValue degreesroemer) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Temperature FromKelvins(double kelvins) - { - double value = (double) kelvins; - return new Temperature(value); - } #else public static Temperature FromKelvins(QuantityValue kelvins) +#endif { double value = (double) kelvins; - return new Temperature((value)); + return new Temperature(value, TemperatureUnit.Kelvin); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -484,28 +451,7 @@ public static Temperature From(double value, TemperatureUnit fromUnit) public static Temperature From(QuantityValue value, TemperatureUnit fromUnit) #endif { - switch (fromUnit) - { - case TemperatureUnit.DegreeCelsius: - return FromDegreesCelsius(value); - case TemperatureUnit.DegreeDelisle: - return FromDegreesDelisle(value); - case TemperatureUnit.DegreeFahrenheit: - return FromDegreesFahrenheit(value); - case TemperatureUnit.DegreeNewton: - return FromDegreesNewton(value); - case TemperatureUnit.DegreeRankine: - return FromDegreesRankine(value); - case TemperatureUnit.DegreeReaumur: - return FromDegreesReaumur(value); - case TemperatureUnit.DegreeRoemer: - return FromDegreesRoemer(value); - case TemperatureUnit.Kelvin: - return FromKelvins(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Temperature((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -522,28 +468,8 @@ public static Temperature From(QuantityValue value, TemperatureUnit fromUnit) { return null; } - switch (fromUnit) - { - case TemperatureUnit.DegreeCelsius: - return FromDegreesCelsius(value.Value); - case TemperatureUnit.DegreeDelisle: - return FromDegreesDelisle(value.Value); - case TemperatureUnit.DegreeFahrenheit: - return FromDegreesFahrenheit(value.Value); - case TemperatureUnit.DegreeNewton: - return FromDegreesNewton(value.Value); - case TemperatureUnit.DegreeRankine: - return FromDegreesRankine(value.Value); - case TemperatureUnit.DegreeReaumur: - return FromDegreesReaumur(value.Value); - case TemperatureUnit.DegreeRoemer: - return FromDegreesRoemer(value.Value); - case TemperatureUnit.Kelvin: - return FromKelvins(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Temperature((double)value.Value, fromUnit); } #endif @@ -562,12 +488,29 @@ public static string GetAbbreviation(TemperatureUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(TemperatureUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + TemperatureUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -589,43 +532,43 @@ public int CompareTo(object obj) #endif int CompareTo(Temperature other) { - return _kelvins.CompareTo(other._kelvins); + return AsBaseUnitKelvins().CompareTo(other.AsBaseUnitKelvins()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Temperature left, Temperature right) { - return left._kelvins <= right._kelvins; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Temperature left, Temperature right) { - return left._kelvins >= right._kelvins; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Temperature left, Temperature right) { - return left._kelvins < right._kelvins; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Temperature left, Temperature right) { - return left._kelvins > right._kelvins; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Temperature left, Temperature right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kelvins == right._kelvins; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Temperature left, Temperature right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kelvins != right._kelvins; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -637,7 +580,7 @@ public override bool Equals(object obj) return false; } - return _kelvins.Equals(((Temperature) obj)._kelvins); + return AsBaseUnitKelvins().Equals(((Temperature) obj).AsBaseUnitKelvins()); } /// @@ -650,12 +593,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Temperature other, Temperature maxError) { - return Math.Abs(_kelvins - other._kelvins) <= maxError._kelvins; + return Math.Abs(AsBaseUnitKelvins() - other.AsBaseUnitKelvins()) <= maxError.AsBaseUnitKelvins(); } public override int GetHashCode() { - return _kelvins.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -665,28 +608,26 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(TemperatureUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitKelvins(); + switch (unit) { - case TemperatureUnit.DegreeCelsius: - return DegreesCelsius; - case TemperatureUnit.DegreeDelisle: - return DegreesDelisle; - case TemperatureUnit.DegreeFahrenheit: - return DegreesFahrenheit; - case TemperatureUnit.DegreeNewton: - return DegreesNewton; - case TemperatureUnit.DegreeRankine: - return DegreesRankine; - case TemperatureUnit.DegreeReaumur: - return DegreesReaumur; - case TemperatureUnit.DegreeRoemer: - return DegreesRoemer; - case TemperatureUnit.Kelvin: - return Kelvins; + case TemperatureUnit.DegreeCelsius: return baseUnitValue - 273.15; + case TemperatureUnit.DegreeDelisle: return (baseUnitValue - 373.15)*-3/2; + case TemperatureUnit.DegreeFahrenheit: return (baseUnitValue - 459.67*5/9)*9/5; + case TemperatureUnit.DegreeNewton: return (baseUnitValue - 273.15)*33/100; + case TemperatureUnit.DegreeRankine: return baseUnitValue*9/5; + case TemperatureUnit.DegreeReaumur: return (baseUnitValue - 273.15)*4/5; + case TemperatureUnit.DegreeRoemer: return (baseUnitValue - (273.15 - 7.5*40d/21))*21/40; + case TemperatureUnit.Kelvin: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -728,7 +669,11 @@ public static Temperature Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -747,17 +692,24 @@ public static Temperature Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Temperature Parse(string str, [CanBeNull] Culture culture) + public static Temperature Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -783,16 +735,41 @@ public static bool TryParse([CanBeNull] string str, out Temperature result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Temperature result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Temperature result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -805,6 +782,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -818,11 +796,14 @@ public static TemperatureUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static TemperatureUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -831,6 +812,8 @@ public static TemperatureUnit ParseUnit(string str, [CanBeNull] string cultureNa /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -843,18 +826,18 @@ public static TemperatureUnit ParseUnit(string str, [CanBeNull] string cultureNa #else public #endif - static TemperatureUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static TemperatureUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == TemperatureUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -863,6 +846,7 @@ static TemperatureUnit ParseUnit(string str, IFormatProvider formatProvider = nu #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Kelvin /// @@ -874,7 +858,7 @@ static TemperatureUnit ParseUnit(string str, IFormatProvider formatProvider = nu /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -891,74 +875,136 @@ public string ToString(TemperatureUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(TemperatureUnit unit, [CanBeNull] Culture culture) + public string ToString( + TemperatureUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(TemperatureUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + TemperatureUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(TemperatureUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + TemperatureUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Temperature /// - public static Temperature MaxValue - { - get - { - return new Temperature(double.MaxValue); - } - } + public static Temperature MaxValue => new Temperature(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Temperature /// - public static Temperature MinValue + public static Temperature MinValue => new Temperature(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitKelvins() { - get + if (Unit == TemperatureUnit.Kelvin) { return _value; } + + switch (Unit) { - return new Temperature(double.MinValue); - } - } - } + case TemperatureUnit.DegreeCelsius: return _value + 273.15; + case TemperatureUnit.DegreeDelisle: return _value*-2/3 + 373.15; + case TemperatureUnit.DegreeFahrenheit: return _value*5/9 + 459.67*5/9; + case TemperatureUnit.DegreeNewton: return _value*100/33 + 273.15; + case TemperatureUnit.DegreeRankine: return _value*5/9; + case TemperatureUnit.DegreeReaumur: return _value*5/4 + 273.15; + case TemperatureUnit.DegreeRoemer: return _value*40/21 + 273.15 - 7.5*40d/21; + case TemperatureUnit.Kelvin: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(TemperatureUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs index 21a5649c26..eba98d0320 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct TemperatureChangeRate : IComparable, IComparable - /// Base unit of TemperatureChangeRate. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. /// - private readonly double _degreesCelsiusPerSecond; + private readonly TemperatureChangeRateUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public TemperatureChangeRate() : this(0) + public TemperatureChangeRate() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public TemperatureChangeRate(double degreescelsiuspersecond) { - _degreesCelsiusPerSecond = Convert.ToDouble(degreescelsiuspersecond); + _value = Convert.ToDouble(degreescelsiuspersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + TemperatureChangeRate(double numericValue, TemperatureChangeRateUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit DegreeCelsiusPerSecond. + /// + /// Value assuming base unit DegreeCelsiusPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - TemperatureChangeRate(long degreescelsiuspersecond) - { - _degreesCelsiusPerSecond = Convert.ToDouble(degreescelsiuspersecond); - } + TemperatureChangeRate(long degreescelsiuspersecond) : this(Convert.ToDouble(degreescelsiuspersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit DegreeCelsiusPerSecond. + /// + /// Value assuming base unit DegreeCelsiusPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - TemperatureChangeRate(decimal degreescelsiuspersecond) - { - _degreesCelsiusPerSecond = Convert.ToDouble(degreescelsiuspersecond); - } + TemperatureChangeRate(decimal degreescelsiuspersecond) : this(Convert.ToDouble(degreescelsiuspersecond), BaseUnit) { } #region Properties @@ -119,104 +156,58 @@ public TemperatureChangeRate(double degreescelsiuspersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static TemperatureChangeRateUnit BaseUnit - { - get { return TemperatureChangeRateUnit.DegreeCelsiusPerSecond; } - } + public static TemperatureChangeRateUnit BaseUnit => TemperatureChangeRateUnit.DegreeCelsiusPerSecond; /// /// All units of measurement for the TemperatureChangeRate quantity. /// public static TemperatureChangeRateUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().ToArray(); - /// /// Get TemperatureChangeRate in CentidegreesCelsiusPerSecond. /// - public double CentidegreesCelsiusPerSecond - { - get { return (_degreesCelsiusPerSecond) / 1e-2d; } - } - + public double CentidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); /// /// Get TemperatureChangeRate in DecadegreesCelsiusPerSecond. /// - public double DecadegreesCelsiusPerSecond - { - get { return (_degreesCelsiusPerSecond) / 1e1d; } - } - + public double DecadegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); /// /// Get TemperatureChangeRate in DecidegreesCelsiusPerSecond. /// - public double DecidegreesCelsiusPerSecond - { - get { return (_degreesCelsiusPerSecond) / 1e-1d; } - } - + public double DecidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); /// /// Get TemperatureChangeRate in DegreesCelsiusPerMinute. /// - public double DegreesCelsiusPerMinute - { - get { return _degreesCelsiusPerSecond*60; } - } - + public double DegreesCelsiusPerMinute => As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); /// /// Get TemperatureChangeRate in DegreesCelsiusPerSecond. /// - public double DegreesCelsiusPerSecond - { - get { return _degreesCelsiusPerSecond; } - } - + public double DegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); /// /// Get TemperatureChangeRate in HectodegreesCelsiusPerSecond. /// - public double HectodegreesCelsiusPerSecond - { - get { return (_degreesCelsiusPerSecond) / 1e2d; } - } - + public double HectodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); /// /// Get TemperatureChangeRate in KilodegreesCelsiusPerSecond. /// - public double KilodegreesCelsiusPerSecond - { - get { return (_degreesCelsiusPerSecond) / 1e3d; } - } - + public double KilodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); /// /// Get TemperatureChangeRate in MicrodegreesCelsiusPerSecond. /// - public double MicrodegreesCelsiusPerSecond - { - get { return (_degreesCelsiusPerSecond) / 1e-6d; } - } - + public double MicrodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); /// /// Get TemperatureChangeRate in MillidegreesCelsiusPerSecond. /// - public double MillidegreesCelsiusPerSecond - { - get { return (_degreesCelsiusPerSecond) / 1e-3d; } - } - + public double MillidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); /// /// Get TemperatureChangeRate in NanodegreesCelsiusPerSecond. /// - public double NanodegreesCelsiusPerSecond - { - get { return (_degreesCelsiusPerSecond) / 1e-9d; } - } + public double NanodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); #endregion #region Static - public static TemperatureChangeRate Zero - { - get { return new TemperatureChangeRate(); } - } + public static TemperatureChangeRate Zero => new TemperatureChangeRate(0, BaseUnit); /// /// Get TemperatureChangeRate from CentidegreesCelsiusPerSecond. @@ -224,17 +215,13 @@ public static TemperatureChangeRate Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(double centidegreescelsiuspersecond) - { - double value = (double) centidegreescelsiuspersecond; - return new TemperatureChangeRate((value) * 1e-2d); - } #else public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(QuantityValue centidegreescelsiuspersecond) +#endif { double value = (double) centidegreescelsiuspersecond; - return new TemperatureChangeRate(((value) * 1e-2d)); + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); } -#endif /// /// Get TemperatureChangeRate from DecadegreesCelsiusPerSecond. @@ -242,17 +229,13 @@ public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(QuantityVal #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(double decadegreescelsiuspersecond) - { - double value = (double) decadegreescelsiuspersecond; - return new TemperatureChangeRate((value) * 1e1d); - } #else public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(QuantityValue decadegreescelsiuspersecond) +#endif { double value = (double) decadegreescelsiuspersecond; - return new TemperatureChangeRate(((value) * 1e1d)); + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); } -#endif /// /// Get TemperatureChangeRate from DecidegreesCelsiusPerSecond. @@ -260,17 +243,13 @@ public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(QuantityValu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(double decidegreescelsiuspersecond) - { - double value = (double) decidegreescelsiuspersecond; - return new TemperatureChangeRate((value) * 1e-1d); - } #else public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(QuantityValue decidegreescelsiuspersecond) +#endif { double value = (double) decidegreescelsiuspersecond; - return new TemperatureChangeRate(((value) * 1e-1d)); + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); } -#endif /// /// Get TemperatureChangeRate from DegreesCelsiusPerMinute. @@ -278,17 +257,13 @@ public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(QuantityValu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureChangeRate FromDegreesCelsiusPerMinute(double degreescelsiusperminute) - { - double value = (double) degreescelsiusperminute; - return new TemperatureChangeRate(value/60); - } #else public static TemperatureChangeRate FromDegreesCelsiusPerMinute(QuantityValue degreescelsiusperminute) +#endif { double value = (double) degreescelsiusperminute; - return new TemperatureChangeRate((value/60)); + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); } -#endif /// /// Get TemperatureChangeRate from DegreesCelsiusPerSecond. @@ -296,17 +271,13 @@ public static TemperatureChangeRate FromDegreesCelsiusPerMinute(QuantityValue de #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureChangeRate FromDegreesCelsiusPerSecond(double degreescelsiuspersecond) - { - double value = (double) degreescelsiuspersecond; - return new TemperatureChangeRate(value); - } #else public static TemperatureChangeRate FromDegreesCelsiusPerSecond(QuantityValue degreescelsiuspersecond) +#endif { double value = (double) degreescelsiuspersecond; - return new TemperatureChangeRate((value)); + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); } -#endif /// /// Get TemperatureChangeRate from HectodegreesCelsiusPerSecond. @@ -314,17 +285,13 @@ public static TemperatureChangeRate FromDegreesCelsiusPerSecond(QuantityValue de #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(double hectodegreescelsiuspersecond) - { - double value = (double) hectodegreescelsiuspersecond; - return new TemperatureChangeRate((value) * 1e2d); - } #else public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(QuantityValue hectodegreescelsiuspersecond) +#endif { double value = (double) hectodegreescelsiuspersecond; - return new TemperatureChangeRate(((value) * 1e2d)); + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); } -#endif /// /// Get TemperatureChangeRate from KilodegreesCelsiusPerSecond. @@ -332,17 +299,13 @@ public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(QuantityVal #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(double kilodegreescelsiuspersecond) - { - double value = (double) kilodegreescelsiuspersecond; - return new TemperatureChangeRate((value) * 1e3d); - } #else public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(QuantityValue kilodegreescelsiuspersecond) +#endif { double value = (double) kilodegreescelsiuspersecond; - return new TemperatureChangeRate(((value) * 1e3d)); + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); } -#endif /// /// Get TemperatureChangeRate from MicrodegreesCelsiusPerSecond. @@ -350,17 +313,13 @@ public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(QuantityValu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(double microdegreescelsiuspersecond) - { - double value = (double) microdegreescelsiuspersecond; - return new TemperatureChangeRate((value) * 1e-6d); - } #else public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(QuantityValue microdegreescelsiuspersecond) +#endif { double value = (double) microdegreescelsiuspersecond; - return new TemperatureChangeRate(((value) * 1e-6d)); + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); } -#endif /// /// Get TemperatureChangeRate from MillidegreesCelsiusPerSecond. @@ -368,17 +327,13 @@ public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(QuantityVal #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(double millidegreescelsiuspersecond) - { - double value = (double) millidegreescelsiuspersecond; - return new TemperatureChangeRate((value) * 1e-3d); - } #else public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(QuantityValue millidegreescelsiuspersecond) +#endif { double value = (double) millidegreescelsiuspersecond; - return new TemperatureChangeRate(((value) * 1e-3d)); + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); } -#endif /// /// Get TemperatureChangeRate from NanodegreesCelsiusPerSecond. @@ -386,17 +341,13 @@ public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(QuantityVal #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(double nanodegreescelsiuspersecond) - { - double value = (double) nanodegreescelsiuspersecond; - return new TemperatureChangeRate((value) * 1e-9d); - } #else public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(QuantityValue nanodegreescelsiuspersecond) +#endif { double value = (double) nanodegreescelsiuspersecond; - return new TemperatureChangeRate(((value) * 1e-9d)); + return new TemperatureChangeRate(value, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -566,32 +517,7 @@ public static TemperatureChangeRate From(double value, TemperatureChangeRateUnit public static TemperatureChangeRate From(QuantityValue value, TemperatureChangeRateUnit fromUnit) #endif { - switch (fromUnit) - { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: - return FromCentidegreesCelsiusPerSecond(value); - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: - return FromDecadegreesCelsiusPerSecond(value); - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: - return FromDecidegreesCelsiusPerSecond(value); - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: - return FromDegreesCelsiusPerMinute(value); - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: - return FromDegreesCelsiusPerSecond(value); - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: - return FromHectodegreesCelsiusPerSecond(value); - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: - return FromKilodegreesCelsiusPerSecond(value); - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: - return FromMicrodegreesCelsiusPerSecond(value); - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: - return FromMillidegreesCelsiusPerSecond(value); - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: - return FromNanodegreesCelsiusPerSecond(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new TemperatureChangeRate((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -608,32 +534,8 @@ public static TemperatureChangeRate From(QuantityValue value, TemperatureChangeR { return null; } - switch (fromUnit) - { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: - return FromCentidegreesCelsiusPerSecond(value.Value); - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: - return FromDecadegreesCelsiusPerSecond(value.Value); - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: - return FromDecidegreesCelsiusPerSecond(value.Value); - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: - return FromDegreesCelsiusPerMinute(value.Value); - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: - return FromDegreesCelsiusPerSecond(value.Value); - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: - return FromHectodegreesCelsiusPerSecond(value.Value); - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: - return FromKilodegreesCelsiusPerSecond(value.Value); - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: - return FromMicrodegreesCelsiusPerSecond(value.Value); - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: - return FromMillidegreesCelsiusPerSecond(value.Value); - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: - return FromNanodegreesCelsiusPerSecond(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new TemperatureChangeRate((double)value.Value, fromUnit); } #endif @@ -652,12 +554,29 @@ public static string GetAbbreviation(TemperatureChangeRateUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(TemperatureChangeRateUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + TemperatureChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -668,37 +587,37 @@ public static string GetAbbreviation(TemperatureChangeRateUnit unit, [CanBeNull] #if !WINDOWS_UWP public static TemperatureChangeRate operator -(TemperatureChangeRate right) { - return new TemperatureChangeRate(-right._degreesCelsiusPerSecond); + return new TemperatureChangeRate(-right.Value, right.Unit); } public static TemperatureChangeRate operator +(TemperatureChangeRate left, TemperatureChangeRate right) { - return new TemperatureChangeRate(left._degreesCelsiusPerSecond + right._degreesCelsiusPerSecond); + return new TemperatureChangeRate(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static TemperatureChangeRate operator -(TemperatureChangeRate left, TemperatureChangeRate right) { - return new TemperatureChangeRate(left._degreesCelsiusPerSecond - right._degreesCelsiusPerSecond); + return new TemperatureChangeRate(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static TemperatureChangeRate operator *(double left, TemperatureChangeRate right) { - return new TemperatureChangeRate(left*right._degreesCelsiusPerSecond); + return new TemperatureChangeRate(left * right.Value, right.Unit); } public static TemperatureChangeRate operator *(TemperatureChangeRate left, double right) { - return new TemperatureChangeRate(left._degreesCelsiusPerSecond*(double)right); + return new TemperatureChangeRate(left.Value * right, left.Unit); } public static TemperatureChangeRate operator /(TemperatureChangeRate left, double right) { - return new TemperatureChangeRate(left._degreesCelsiusPerSecond/(double)right); + return new TemperatureChangeRate(left.Value / right, left.Unit); } public static double operator /(TemperatureChangeRate left, TemperatureChangeRate right) { - return Convert.ToDouble(left._degreesCelsiusPerSecond/right._degreesCelsiusPerSecond); + return left.DegreesCelsiusPerSecond / right.DegreesCelsiusPerSecond; } #endif @@ -721,43 +640,43 @@ public int CompareTo(object obj) #endif int CompareTo(TemperatureChangeRate other) { - return _degreesCelsiusPerSecond.CompareTo(other._degreesCelsiusPerSecond); + return AsBaseUnitDegreesCelsiusPerSecond().CompareTo(other.AsBaseUnitDegreesCelsiusPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(TemperatureChangeRate left, TemperatureChangeRate right) { - return left._degreesCelsiusPerSecond <= right._degreesCelsiusPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(TemperatureChangeRate left, TemperatureChangeRate right) { - return left._degreesCelsiusPerSecond >= right._degreesCelsiusPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(TemperatureChangeRate left, TemperatureChangeRate right) { - return left._degreesCelsiusPerSecond < right._degreesCelsiusPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(TemperatureChangeRate left, TemperatureChangeRate right) { - return left._degreesCelsiusPerSecond > right._degreesCelsiusPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(TemperatureChangeRate left, TemperatureChangeRate right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._degreesCelsiusPerSecond == right._degreesCelsiusPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(TemperatureChangeRate left, TemperatureChangeRate right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._degreesCelsiusPerSecond != right._degreesCelsiusPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -769,7 +688,7 @@ public override bool Equals(object obj) return false; } - return _degreesCelsiusPerSecond.Equals(((TemperatureChangeRate) obj)._degreesCelsiusPerSecond); + return AsBaseUnitDegreesCelsiusPerSecond().Equals(((TemperatureChangeRate) obj).AsBaseUnitDegreesCelsiusPerSecond()); } /// @@ -782,12 +701,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(TemperatureChangeRate other, TemperatureChangeRate maxError) { - return Math.Abs(_degreesCelsiusPerSecond - other._degreesCelsiusPerSecond) <= maxError._degreesCelsiusPerSecond; + return Math.Abs(AsBaseUnitDegreesCelsiusPerSecond() - other.AsBaseUnitDegreesCelsiusPerSecond()) <= maxError.AsBaseUnitDegreesCelsiusPerSecond(); } public override int GetHashCode() { - return _degreesCelsiusPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -797,32 +716,28 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(TemperatureChangeRateUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitDegreesCelsiusPerSecond(); + switch (unit) { - case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: - return CentidegreesCelsiusPerSecond; - case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: - return DecadegreesCelsiusPerSecond; - case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: - return DecidegreesCelsiusPerSecond; - case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: - return DegreesCelsiusPerMinute; - case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: - return DegreesCelsiusPerSecond; - case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: - return HectodegreesCelsiusPerSecond; - case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: - return KilodegreesCelsiusPerSecond; - case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: - return MicrodegreesCelsiusPerSecond; - case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: - return MillidegreesCelsiusPerSecond; - case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: - return NanodegreesCelsiusPerSecond; + case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-2d; + case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: return (baseUnitValue) / 1e1d; + case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-1d; + case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: return baseUnitValue*60; + case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: return baseUnitValue; + case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: return (baseUnitValue) / 1e2d; + case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: return (baseUnitValue) / 1e3d; + case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: return (baseUnitValue) / 1e-6d; + case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: return (baseUnitValue) / 1e-3d; + case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: return (baseUnitValue) / 1e-9d; default: throw new NotImplementedException("unit: " + unit); @@ -864,7 +779,11 @@ public static TemperatureChangeRate Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -883,17 +802,24 @@ public static TemperatureChangeRate Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static TemperatureChangeRate Parse(string str, [CanBeNull] Culture culture) + public static TemperatureChangeRate Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -919,16 +845,41 @@ public static bool TryParse([CanBeNull] string str, out TemperatureChangeRate re /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out TemperatureChangeRate result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out TemperatureChangeRate result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -941,6 +892,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -954,11 +906,14 @@ public static TemperatureChangeRateUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static TemperatureChangeRateUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -967,6 +922,8 @@ public static TemperatureChangeRateUnit ParseUnit(string str, [CanBeNull] string /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -979,18 +936,18 @@ public static TemperatureChangeRateUnit ParseUnit(string str, [CanBeNull] string #else public #endif - static TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == TemperatureChangeRateUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureChangeRateUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -999,6 +956,7 @@ static TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider formatPro #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is DegreeCelsiusPerSecond /// @@ -1010,7 +968,7 @@ static TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider formatPro /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1027,74 +985,138 @@ public string ToString(TemperatureChangeRateUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(TemperatureChangeRateUnit unit, [CanBeNull] Culture culture) + public string ToString( + TemperatureChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(TemperatureChangeRateUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + TemperatureChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(TemperatureChangeRateUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + TemperatureChangeRateUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of TemperatureChangeRate /// - public static TemperatureChangeRate MaxValue - { - get - { - return new TemperatureChangeRate(double.MaxValue); - } - } + public static TemperatureChangeRate MaxValue => new TemperatureChangeRate(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of TemperatureChangeRate /// - public static TemperatureChangeRate MinValue + public static TemperatureChangeRate MinValue => new TemperatureChangeRate(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitDegreesCelsiusPerSecond() { - get + if (Unit == TemperatureChangeRateUnit.DegreeCelsiusPerSecond) { return _value; } + + switch (Unit) { - return new TemperatureChangeRate(double.MinValue); - } - } - } + case TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond: return (_value) * 1e-2d; + case TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond: return (_value) * 1e1d; + case TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond: return (_value) * 1e-1d; + case TemperatureChangeRateUnit.DegreeCelsiusPerMinute: return _value/60; + case TemperatureChangeRateUnit.DegreeCelsiusPerSecond: return _value; + case TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond: return (_value) * 1e2d; + case TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond: return (_value) * 1e3d; + case TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond: return (_value) * 1e-6d; + case TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond: return (_value) * 1e-3d; + case TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond: return (_value) * 1e-9d; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(TemperatureChangeRateUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs index 0de68fd658..614416b3a0 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct TemperatureDelta : IComparable, IComparable - /// Base unit of TemperatureDelta. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TemperatureDeltaUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _kelvins; + public TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public TemperatureDelta() : this(0) + public TemperatureDelta() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public TemperatureDelta(double kelvins) { - _kelvins = Convert.ToDouble(kelvins); + _value = Convert.ToDouble(kelvins); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + TemperatureDelta(double numericValue, TemperatureDeltaUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit Kelvin. + /// + /// Value assuming base unit Kelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - TemperatureDelta(long kelvins) - { - _kelvins = Convert.ToDouble(kelvins); - } + TemperatureDelta(long kelvins) : this(Convert.ToDouble(kelvins), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit Kelvin. + /// + /// Value assuming base unit Kelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - TemperatureDelta(decimal kelvins) - { - _kelvins = Convert.ToDouble(kelvins); - } + TemperatureDelta(decimal kelvins) : this(Convert.ToDouble(kelvins), BaseUnit) { } #region Properties @@ -119,160 +156,90 @@ public TemperatureDelta(double kelvins) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static TemperatureDeltaUnit BaseUnit - { - get { return TemperatureDeltaUnit.Kelvin; } - } + public static TemperatureDeltaUnit BaseUnit => TemperatureDeltaUnit.Kelvin; /// /// All units of measurement for the TemperatureDelta quantity. /// public static TemperatureDeltaUnit[] Units { get; } = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().ToArray(); - /// /// Get TemperatureDelta in DegreesCelsius. /// - public double DegreesCelsius - { - get { return _kelvins; } - } - + public double DegreesCelsius => As(TemperatureDeltaUnit.DegreeCelsius); /// /// Get TemperatureDelta in DegreesCelsiusDelta. /// [System.Obsolete("Deprecated due to github issue #180, please use DegreeCelsius instead")] - public double DegreesCelsiusDelta - { - get { return _kelvins; } - } - + public double DegreesCelsiusDelta => As(TemperatureDeltaUnit.DegreeCelsiusDelta); /// /// Get TemperatureDelta in DegreesDelisle. /// - public double DegreesDelisle - { - get { return _kelvins*-3/2; } - } - + public double DegreesDelisle => As(TemperatureDeltaUnit.DegreeDelisle); /// /// Get TemperatureDelta in DegreesDelisleDelta. /// [System.Obsolete("Deprecated due to github issue #180, please use DegreeDelisle instead")] - public double DegreesDelisleDelta - { - get { return _kelvins*-3/2; } - } - + public double DegreesDelisleDelta => As(TemperatureDeltaUnit.DegreeDelisleDelta); /// /// Get TemperatureDelta in DegreesFahrenheit. /// - public double DegreesFahrenheit - { - get { return _kelvins*9/5; } - } - + public double DegreesFahrenheit => As(TemperatureDeltaUnit.DegreeFahrenheit); /// /// Get TemperatureDelta in DegreesFahrenheitDelta. /// [System.Obsolete("Deprecated due to github issue #180, please use DegreeFahrenheit instead")] - public double DegreesFahrenheitDelta - { - get { return _kelvins*9/5; } - } - + public double DegreesFahrenheitDelta => As(TemperatureDeltaUnit.DegreeFahrenheitDelta); /// /// Get TemperatureDelta in DegreesNewton. /// - public double DegreesNewton - { - get { return _kelvins*33/100; } - } - + public double DegreesNewton => As(TemperatureDeltaUnit.DegreeNewton); /// /// Get TemperatureDelta in DegreesNewtonDelta. /// [System.Obsolete("Deprecated due to github issue #180, please use DegreeNewton instead")] - public double DegreesNewtonDelta - { - get { return _kelvins*33/100; } - } - + public double DegreesNewtonDelta => As(TemperatureDeltaUnit.DegreeNewtonDelta); /// /// Get TemperatureDelta in DegreesRankine. /// - public double DegreesRankine - { - get { return _kelvins*9/5; } - } - + public double DegreesRankine => As(TemperatureDeltaUnit.DegreeRankine); /// /// Get TemperatureDelta in DegreesRankineDelta. /// [System.Obsolete("Deprecated due to github issue #180, please use DegreeRankine instead")] - public double DegreesRankineDelta - { - get { return _kelvins*9/5; } - } - + public double DegreesRankineDelta => As(TemperatureDeltaUnit.DegreeRankineDelta); /// /// Get TemperatureDelta in DegreesReaumur. /// - public double DegreesReaumur - { - get { return _kelvins*4/5; } - } - + public double DegreesReaumur => As(TemperatureDeltaUnit.DegreeReaumur); /// /// Get TemperatureDelta in DegreesReaumurDelta. /// [System.Obsolete("Deprecated due to github issue #180, please use DegreeReaumur instead")] - public double DegreesReaumurDelta - { - get { return _kelvins*4/5; } - } - + public double DegreesReaumurDelta => As(TemperatureDeltaUnit.DegreeReaumurDelta); /// /// Get TemperatureDelta in DegreesRoemer. /// - public double DegreesRoemer - { - get { return _kelvins*21/40; } - } - + public double DegreesRoemer => As(TemperatureDeltaUnit.DegreeRoemer); /// /// Get TemperatureDelta in DegreesRoemerDelta. /// [System.Obsolete("Deprecated due to github issue #180, please use DegreeRoemer instead")] - public double DegreesRoemerDelta - { - get { return _kelvins*21/40; } - } - + public double DegreesRoemerDelta => As(TemperatureDeltaUnit.DegreeRoemerDelta); /// /// Get TemperatureDelta in Kelvins. /// - public double Kelvins - { - get { return _kelvins; } - } - + public double Kelvins => As(TemperatureDeltaUnit.Kelvin); /// /// Get TemperatureDelta in KelvinsDelta. /// [System.Obsolete("Deprecated due to github issue #180, please use Kelvin instead")] - public double KelvinsDelta - { - get { return _kelvins; } - } + public double KelvinsDelta => As(TemperatureDeltaUnit.KelvinDelta); #endregion #region Static - public static TemperatureDelta Zero - { - get { return new TemperatureDelta(); } - } + public static TemperatureDelta Zero => new TemperatureDelta(0, BaseUnit); /// /// Get TemperatureDelta from DegreesCelsius. @@ -280,17 +247,13 @@ public static TemperatureDelta Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesCelsius(double degreescelsius) - { - double value = (double) degreescelsius; - return new TemperatureDelta(value); - } #else public static TemperatureDelta FromDegreesCelsius(QuantityValue degreescelsius) +#endif { double value = (double) degreescelsius; - return new TemperatureDelta((value)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); } -#endif /// /// Get TemperatureDelta from DegreesCelsiusDelta. @@ -298,17 +261,13 @@ public static TemperatureDelta FromDegreesCelsius(QuantityValue degreescelsius) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesCelsiusDelta(double degreescelsiusdelta) - { - double value = (double) degreescelsiusdelta; - return new TemperatureDelta(value); - } #else public static TemperatureDelta FromDegreesCelsiusDelta(QuantityValue degreescelsiusdelta) +#endif { double value = (double) degreescelsiusdelta; - return new TemperatureDelta((value)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsiusDelta); } -#endif /// /// Get TemperatureDelta from DegreesDelisle. @@ -316,17 +275,13 @@ public static TemperatureDelta FromDegreesCelsiusDelta(QuantityValue degreescels #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesDelisle(double degreesdelisle) - { - double value = (double) degreesdelisle; - return new TemperatureDelta(value*-2/3); - } #else public static TemperatureDelta FromDegreesDelisle(QuantityValue degreesdelisle) +#endif { double value = (double) degreesdelisle; - return new TemperatureDelta((value*-2/3)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); } -#endif /// /// Get TemperatureDelta from DegreesDelisleDelta. @@ -334,17 +289,13 @@ public static TemperatureDelta FromDegreesDelisle(QuantityValue degreesdelisle) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesDelisleDelta(double degreesdelisledelta) - { - double value = (double) degreesdelisledelta; - return new TemperatureDelta(value*-2/3); - } #else public static TemperatureDelta FromDegreesDelisleDelta(QuantityValue degreesdelisledelta) +#endif { double value = (double) degreesdelisledelta; - return new TemperatureDelta((value*-2/3)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisleDelta); } -#endif /// /// Get TemperatureDelta from DegreesFahrenheit. @@ -352,17 +303,13 @@ public static TemperatureDelta FromDegreesDelisleDelta(QuantityValue degreesdeli #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesFahrenheit(double degreesfahrenheit) - { - double value = (double) degreesfahrenheit; - return new TemperatureDelta(value*5/9); - } #else public static TemperatureDelta FromDegreesFahrenheit(QuantityValue degreesfahrenheit) +#endif { double value = (double) degreesfahrenheit; - return new TemperatureDelta((value*5/9)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); } -#endif /// /// Get TemperatureDelta from DegreesFahrenheitDelta. @@ -370,17 +317,13 @@ public static TemperatureDelta FromDegreesFahrenheit(QuantityValue degreesfahren #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesFahrenheitDelta(double degreesfahrenheitdelta) - { - double value = (double) degreesfahrenheitdelta; - return new TemperatureDelta(value*5/9); - } #else public static TemperatureDelta FromDegreesFahrenheitDelta(QuantityValue degreesfahrenheitdelta) +#endif { double value = (double) degreesfahrenheitdelta; - return new TemperatureDelta((value*5/9)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheitDelta); } -#endif /// /// Get TemperatureDelta from DegreesNewton. @@ -388,17 +331,13 @@ public static TemperatureDelta FromDegreesFahrenheitDelta(QuantityValue degreesf #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesNewton(double degreesnewton) - { - double value = (double) degreesnewton; - return new TemperatureDelta(value*100/33); - } #else public static TemperatureDelta FromDegreesNewton(QuantityValue degreesnewton) +#endif { double value = (double) degreesnewton; - return new TemperatureDelta((value*100/33)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); } -#endif /// /// Get TemperatureDelta from DegreesNewtonDelta. @@ -406,17 +345,13 @@ public static TemperatureDelta FromDegreesNewton(QuantityValue degreesnewton) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesNewtonDelta(double degreesnewtondelta) - { - double value = (double) degreesnewtondelta; - return new TemperatureDelta(value*100/33); - } #else public static TemperatureDelta FromDegreesNewtonDelta(QuantityValue degreesnewtondelta) +#endif { double value = (double) degreesnewtondelta; - return new TemperatureDelta((value*100/33)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewtonDelta); } -#endif /// /// Get TemperatureDelta from DegreesRankine. @@ -424,17 +359,13 @@ public static TemperatureDelta FromDegreesNewtonDelta(QuantityValue degreesnewto #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesRankine(double degreesrankine) - { - double value = (double) degreesrankine; - return new TemperatureDelta(value*5/9); - } #else public static TemperatureDelta FromDegreesRankine(QuantityValue degreesrankine) +#endif { double value = (double) degreesrankine; - return new TemperatureDelta((value*5/9)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); } -#endif /// /// Get TemperatureDelta from DegreesRankineDelta. @@ -442,17 +373,13 @@ public static TemperatureDelta FromDegreesRankine(QuantityValue degreesrankine) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesRankineDelta(double degreesrankinedelta) - { - double value = (double) degreesrankinedelta; - return new TemperatureDelta(value*5/9); - } #else public static TemperatureDelta FromDegreesRankineDelta(QuantityValue degreesrankinedelta) +#endif { double value = (double) degreesrankinedelta; - return new TemperatureDelta((value*5/9)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankineDelta); } -#endif /// /// Get TemperatureDelta from DegreesReaumur. @@ -460,17 +387,13 @@ public static TemperatureDelta FromDegreesRankineDelta(QuantityValue degreesrank #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesReaumur(double degreesreaumur) - { - double value = (double) degreesreaumur; - return new TemperatureDelta(value*5/4); - } #else public static TemperatureDelta FromDegreesReaumur(QuantityValue degreesreaumur) +#endif { double value = (double) degreesreaumur; - return new TemperatureDelta((value*5/4)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); } -#endif /// /// Get TemperatureDelta from DegreesReaumurDelta. @@ -478,17 +401,13 @@ public static TemperatureDelta FromDegreesReaumur(QuantityValue degreesreaumur) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesReaumurDelta(double degreesreaumurdelta) - { - double value = (double) degreesreaumurdelta; - return new TemperatureDelta(value*5/4); - } #else public static TemperatureDelta FromDegreesReaumurDelta(QuantityValue degreesreaumurdelta) +#endif { double value = (double) degreesreaumurdelta; - return new TemperatureDelta((value*5/4)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumurDelta); } -#endif /// /// Get TemperatureDelta from DegreesRoemer. @@ -496,17 +415,13 @@ public static TemperatureDelta FromDegreesReaumurDelta(QuantityValue degreesreau #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesRoemer(double degreesroemer) - { - double value = (double) degreesroemer; - return new TemperatureDelta(value*40/21); - } #else public static TemperatureDelta FromDegreesRoemer(QuantityValue degreesroemer) +#endif { double value = (double) degreesroemer; - return new TemperatureDelta((value*40/21)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); } -#endif /// /// Get TemperatureDelta from DegreesRoemerDelta. @@ -514,17 +429,13 @@ public static TemperatureDelta FromDegreesRoemer(QuantityValue degreesroemer) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromDegreesRoemerDelta(double degreesroemerdelta) - { - double value = (double) degreesroemerdelta; - return new TemperatureDelta(value*40/21); - } #else public static TemperatureDelta FromDegreesRoemerDelta(QuantityValue degreesroemerdelta) +#endif { double value = (double) degreesroemerdelta; - return new TemperatureDelta((value*40/21)); + return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemerDelta); } -#endif /// /// Get TemperatureDelta from Kelvins. @@ -532,17 +443,13 @@ public static TemperatureDelta FromDegreesRoemerDelta(QuantityValue degreesroeme #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromKelvins(double kelvins) - { - double value = (double) kelvins; - return new TemperatureDelta(value); - } #else public static TemperatureDelta FromKelvins(QuantityValue kelvins) +#endif { double value = (double) kelvins; - return new TemperatureDelta((value)); + return new TemperatureDelta(value, TemperatureDeltaUnit.Kelvin); } -#endif /// /// Get TemperatureDelta from KelvinsDelta. @@ -550,17 +457,13 @@ public static TemperatureDelta FromKelvins(QuantityValue kelvins) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static TemperatureDelta FromKelvinsDelta(double kelvinsdelta) - { - double value = (double) kelvinsdelta; - return new TemperatureDelta(value); - } #else public static TemperatureDelta FromKelvinsDelta(QuantityValue kelvinsdelta) +#endif { double value = (double) kelvinsdelta; - return new TemperatureDelta((value)); + return new TemperatureDelta(value, TemperatureDeltaUnit.KelvinDelta); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -820,44 +723,7 @@ public static TemperatureDelta From(double value, TemperatureDeltaUnit fromUnit) public static TemperatureDelta From(QuantityValue value, TemperatureDeltaUnit fromUnit) #endif { - switch (fromUnit) - { - case TemperatureDeltaUnit.DegreeCelsius: - return FromDegreesCelsius(value); - case TemperatureDeltaUnit.DegreeCelsiusDelta: - return FromDegreesCelsiusDelta(value); - case TemperatureDeltaUnit.DegreeDelisle: - return FromDegreesDelisle(value); - case TemperatureDeltaUnit.DegreeDelisleDelta: - return FromDegreesDelisleDelta(value); - case TemperatureDeltaUnit.DegreeFahrenheit: - return FromDegreesFahrenheit(value); - case TemperatureDeltaUnit.DegreeFahrenheitDelta: - return FromDegreesFahrenheitDelta(value); - case TemperatureDeltaUnit.DegreeNewton: - return FromDegreesNewton(value); - case TemperatureDeltaUnit.DegreeNewtonDelta: - return FromDegreesNewtonDelta(value); - case TemperatureDeltaUnit.DegreeRankine: - return FromDegreesRankine(value); - case TemperatureDeltaUnit.DegreeRankineDelta: - return FromDegreesRankineDelta(value); - case TemperatureDeltaUnit.DegreeReaumur: - return FromDegreesReaumur(value); - case TemperatureDeltaUnit.DegreeReaumurDelta: - return FromDegreesReaumurDelta(value); - case TemperatureDeltaUnit.DegreeRoemer: - return FromDegreesRoemer(value); - case TemperatureDeltaUnit.DegreeRoemerDelta: - return FromDegreesRoemerDelta(value); - case TemperatureDeltaUnit.Kelvin: - return FromKelvins(value); - case TemperatureDeltaUnit.KelvinDelta: - return FromKelvinsDelta(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new TemperatureDelta((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -874,44 +740,8 @@ public static TemperatureDelta From(QuantityValue value, TemperatureDeltaUnit fr { return null; } - switch (fromUnit) - { - case TemperatureDeltaUnit.DegreeCelsius: - return FromDegreesCelsius(value.Value); - case TemperatureDeltaUnit.DegreeCelsiusDelta: - return FromDegreesCelsiusDelta(value.Value); - case TemperatureDeltaUnit.DegreeDelisle: - return FromDegreesDelisle(value.Value); - case TemperatureDeltaUnit.DegreeDelisleDelta: - return FromDegreesDelisleDelta(value.Value); - case TemperatureDeltaUnit.DegreeFahrenheit: - return FromDegreesFahrenheit(value.Value); - case TemperatureDeltaUnit.DegreeFahrenheitDelta: - return FromDegreesFahrenheitDelta(value.Value); - case TemperatureDeltaUnit.DegreeNewton: - return FromDegreesNewton(value.Value); - case TemperatureDeltaUnit.DegreeNewtonDelta: - return FromDegreesNewtonDelta(value.Value); - case TemperatureDeltaUnit.DegreeRankine: - return FromDegreesRankine(value.Value); - case TemperatureDeltaUnit.DegreeRankineDelta: - return FromDegreesRankineDelta(value.Value); - case TemperatureDeltaUnit.DegreeReaumur: - return FromDegreesReaumur(value.Value); - case TemperatureDeltaUnit.DegreeReaumurDelta: - return FromDegreesReaumurDelta(value.Value); - case TemperatureDeltaUnit.DegreeRoemer: - return FromDegreesRoemer(value.Value); - case TemperatureDeltaUnit.DegreeRoemerDelta: - return FromDegreesRoemerDelta(value.Value); - case TemperatureDeltaUnit.Kelvin: - return FromKelvins(value.Value); - case TemperatureDeltaUnit.KelvinDelta: - return FromKelvinsDelta(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new TemperatureDelta((double)value.Value, fromUnit); } #endif @@ -930,12 +760,29 @@ public static string GetAbbreviation(TemperatureDeltaUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(TemperatureDeltaUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + TemperatureDeltaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -946,37 +793,37 @@ public static string GetAbbreviation(TemperatureDeltaUnit unit, [CanBeNull] Cult #if !WINDOWS_UWP public static TemperatureDelta operator -(TemperatureDelta right) { - return new TemperatureDelta(-right._kelvins); + return new TemperatureDelta(-right.Value, right.Unit); } public static TemperatureDelta operator +(TemperatureDelta left, TemperatureDelta right) { - return new TemperatureDelta(left._kelvins + right._kelvins); + return new TemperatureDelta(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static TemperatureDelta operator -(TemperatureDelta left, TemperatureDelta right) { - return new TemperatureDelta(left._kelvins - right._kelvins); + return new TemperatureDelta(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static TemperatureDelta operator *(double left, TemperatureDelta right) { - return new TemperatureDelta(left*right._kelvins); + return new TemperatureDelta(left * right.Value, right.Unit); } public static TemperatureDelta operator *(TemperatureDelta left, double right) { - return new TemperatureDelta(left._kelvins*(double)right); + return new TemperatureDelta(left.Value * right, left.Unit); } public static TemperatureDelta operator /(TemperatureDelta left, double right) { - return new TemperatureDelta(left._kelvins/(double)right); + return new TemperatureDelta(left.Value / right, left.Unit); } public static double operator /(TemperatureDelta left, TemperatureDelta right) { - return Convert.ToDouble(left._kelvins/right._kelvins); + return left.Kelvins / right.Kelvins; } #endif @@ -999,43 +846,43 @@ public int CompareTo(object obj) #endif int CompareTo(TemperatureDelta other) { - return _kelvins.CompareTo(other._kelvins); + return AsBaseUnitKelvins().CompareTo(other.AsBaseUnitKelvins()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(TemperatureDelta left, TemperatureDelta right) { - return left._kelvins <= right._kelvins; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(TemperatureDelta left, TemperatureDelta right) { - return left._kelvins >= right._kelvins; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(TemperatureDelta left, TemperatureDelta right) { - return left._kelvins < right._kelvins; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(TemperatureDelta left, TemperatureDelta right) { - return left._kelvins > right._kelvins; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(TemperatureDelta left, TemperatureDelta right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kelvins == right._kelvins; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(TemperatureDelta left, TemperatureDelta right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._kelvins != right._kelvins; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1047,7 +894,7 @@ public override bool Equals(object obj) return false; } - return _kelvins.Equals(((TemperatureDelta) obj)._kelvins); + return AsBaseUnitKelvins().Equals(((TemperatureDelta) obj).AsBaseUnitKelvins()); } /// @@ -1060,12 +907,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(TemperatureDelta other, TemperatureDelta maxError) { - return Math.Abs(_kelvins - other._kelvins) <= maxError._kelvins; + return Math.Abs(AsBaseUnitKelvins() - other.AsBaseUnitKelvins()) <= maxError.AsBaseUnitKelvins(); } public override int GetHashCode() { - return _kelvins.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1075,44 +922,34 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(TemperatureDeltaUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitKelvins(); + switch (unit) { - case TemperatureDeltaUnit.DegreeCelsius: - return DegreesCelsius; - case TemperatureDeltaUnit.DegreeCelsiusDelta: - return DegreesCelsiusDelta; - case TemperatureDeltaUnit.DegreeDelisle: - return DegreesDelisle; - case TemperatureDeltaUnit.DegreeDelisleDelta: - return DegreesDelisleDelta; - case TemperatureDeltaUnit.DegreeFahrenheit: - return DegreesFahrenheit; - case TemperatureDeltaUnit.DegreeFahrenheitDelta: - return DegreesFahrenheitDelta; - case TemperatureDeltaUnit.DegreeNewton: - return DegreesNewton; - case TemperatureDeltaUnit.DegreeNewtonDelta: - return DegreesNewtonDelta; - case TemperatureDeltaUnit.DegreeRankine: - return DegreesRankine; - case TemperatureDeltaUnit.DegreeRankineDelta: - return DegreesRankineDelta; - case TemperatureDeltaUnit.DegreeReaumur: - return DegreesReaumur; - case TemperatureDeltaUnit.DegreeReaumurDelta: - return DegreesReaumurDelta; - case TemperatureDeltaUnit.DegreeRoemer: - return DegreesRoemer; - case TemperatureDeltaUnit.DegreeRoemerDelta: - return DegreesRoemerDelta; - case TemperatureDeltaUnit.Kelvin: - return Kelvins; - case TemperatureDeltaUnit.KelvinDelta: - return KelvinsDelta; + case TemperatureDeltaUnit.DegreeCelsius: return baseUnitValue; + case TemperatureDeltaUnit.DegreeCelsiusDelta: return baseUnitValue; + case TemperatureDeltaUnit.DegreeDelisle: return baseUnitValue*-3/2; + case TemperatureDeltaUnit.DegreeDelisleDelta: return baseUnitValue*-3/2; + case TemperatureDeltaUnit.DegreeFahrenheit: return baseUnitValue*9/5; + case TemperatureDeltaUnit.DegreeFahrenheitDelta: return baseUnitValue*9/5; + case TemperatureDeltaUnit.DegreeNewton: return baseUnitValue*33/100; + case TemperatureDeltaUnit.DegreeNewtonDelta: return baseUnitValue*33/100; + case TemperatureDeltaUnit.DegreeRankine: return baseUnitValue*9/5; + case TemperatureDeltaUnit.DegreeRankineDelta: return baseUnitValue*9/5; + case TemperatureDeltaUnit.DegreeReaumur: return baseUnitValue*4/5; + case TemperatureDeltaUnit.DegreeReaumurDelta: return baseUnitValue*4/5; + case TemperatureDeltaUnit.DegreeRoemer: return baseUnitValue*21/40; + case TemperatureDeltaUnit.DegreeRoemerDelta: return baseUnitValue*21/40; + case TemperatureDeltaUnit.Kelvin: return baseUnitValue; + case TemperatureDeltaUnit.KelvinDelta: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -1154,7 +991,11 @@ public static TemperatureDelta Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1173,17 +1014,24 @@ public static TemperatureDelta Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static TemperatureDelta Parse(string str, [CanBeNull] Culture culture) + public static TemperatureDelta Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1209,16 +1057,41 @@ public static bool TryParse([CanBeNull] string str, out TemperatureDelta result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out TemperatureDelta result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out TemperatureDelta result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1231,6 +1104,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1244,11 +1118,14 @@ public static TemperatureDeltaUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static TemperatureDeltaUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1257,6 +1134,8 @@ public static TemperatureDeltaUnit ParseUnit(string str, [CanBeNull] string cult /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1269,18 +1148,18 @@ public static TemperatureDeltaUnit ParseUnit(string str, [CanBeNull] string cult #else public #endif - static TemperatureDeltaUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static TemperatureDeltaUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == TemperatureDeltaUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TemperatureDeltaUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1289,6 +1168,7 @@ static TemperatureDeltaUnit ParseUnit(string str, IFormatProvider formatProvider #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is Kelvin /// @@ -1300,7 +1180,7 @@ static TemperatureDeltaUnit ParseUnit(string str, IFormatProvider formatProvider /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1317,74 +1197,144 @@ public string ToString(TemperatureDeltaUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(TemperatureDeltaUnit unit, [CanBeNull] Culture culture) + public string ToString( + TemperatureDeltaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(TemperatureDeltaUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + TemperatureDeltaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(TemperatureDeltaUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + TemperatureDeltaUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of TemperatureDelta /// - public static TemperatureDelta MaxValue - { - get - { - return new TemperatureDelta(double.MaxValue); - } - } + public static TemperatureDelta MaxValue => new TemperatureDelta(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of TemperatureDelta /// - public static TemperatureDelta MinValue + public static TemperatureDelta MinValue => new TemperatureDelta(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitKelvins() { - get + if (Unit == TemperatureDeltaUnit.Kelvin) { return _value; } + + switch (Unit) { - return new TemperatureDelta(double.MinValue); - } - } - } + case TemperatureDeltaUnit.DegreeCelsius: return _value; + case TemperatureDeltaUnit.DegreeCelsiusDelta: return _value; + case TemperatureDeltaUnit.DegreeDelisle: return _value*-2/3; + case TemperatureDeltaUnit.DegreeDelisleDelta: return _value*-2/3; + case TemperatureDeltaUnit.DegreeFahrenheit: return _value*5/9; + case TemperatureDeltaUnit.DegreeFahrenheitDelta: return _value*5/9; + case TemperatureDeltaUnit.DegreeNewton: return _value*100/33; + case TemperatureDeltaUnit.DegreeNewtonDelta: return _value*100/33; + case TemperatureDeltaUnit.DegreeRankine: return _value*5/9; + case TemperatureDeltaUnit.DegreeRankineDelta: return _value*5/9; + case TemperatureDeltaUnit.DegreeReaumur: return _value*5/4; + case TemperatureDeltaUnit.DegreeReaumurDelta: return _value*5/4; + case TemperatureDeltaUnit.DegreeRoemer: return _value*40/21; + case TemperatureDeltaUnit.DegreeRoemerDelta: return _value*40/21; + case TemperatureDeltaUnit.Kelvin: return _value; + case TemperatureDeltaUnit.KelvinDelta: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(TemperatureDeltaUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs index 4b6a5ea739..4d228333d7 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ThermalConductivity : IComparable, IComparable - /// Base unit of ThermalConductivity. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ThermalConductivityUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _wattsPerMeterKelvin; + public ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ThermalConductivity() : this(0) + public ThermalConductivity() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ThermalConductivity(double wattspermeterkelvin) { - _wattsPerMeterKelvin = Convert.ToDouble(wattspermeterkelvin); + _value = Convert.ToDouble(wattspermeterkelvin); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ThermalConductivity(double numericValue, ThermalConductivityUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit WattPerMeterKelvin. + /// + /// Value assuming base unit WattPerMeterKelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ThermalConductivity(long wattspermeterkelvin) - { - _wattsPerMeterKelvin = Convert.ToDouble(wattspermeterkelvin); - } + ThermalConductivity(long wattspermeterkelvin) : this(Convert.ToDouble(wattspermeterkelvin), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit WattPerMeterKelvin. + /// + /// Value assuming base unit WattPerMeterKelvin. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ThermalConductivity(decimal wattspermeterkelvin) - { - _wattsPerMeterKelvin = Convert.ToDouble(wattspermeterkelvin); - } + ThermalConductivity(decimal wattspermeterkelvin) : this(Convert.ToDouble(wattspermeterkelvin), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public ThermalConductivity(double wattspermeterkelvin) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ThermalConductivityUnit BaseUnit - { - get { return ThermalConductivityUnit.WattPerMeterKelvin; } - } + public static ThermalConductivityUnit BaseUnit => ThermalConductivityUnit.WattPerMeterKelvin; /// /// All units of measurement for the ThermalConductivity quantity. /// public static ThermalConductivityUnit[] Units { get; } = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().ToArray(); - /// /// Get ThermalConductivity in WattsPerMeterKelvin. /// - public double WattsPerMeterKelvin - { - get { return _wattsPerMeterKelvin; } - } + public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); #endregion #region Static - public static ThermalConductivity Zero - { - get { return new ThermalConductivity(); } - } + public static ThermalConductivity Zero => new ThermalConductivity(0, BaseUnit); /// /// Get ThermalConductivity from WattsPerMeterKelvin. @@ -152,17 +179,13 @@ public static ThermalConductivity Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ThermalConductivity FromWattsPerMeterKelvin(double wattspermeterkelvin) - { - double value = (double) wattspermeterkelvin; - return new ThermalConductivity(value); - } #else public static ThermalConductivity FromWattsPerMeterKelvin(QuantityValue wattspermeterkelvin) +#endif { double value = (double) wattspermeterkelvin; - return new ThermalConductivity((value)); + return new ThermalConductivity(value, ThermalConductivityUnit.WattPerMeterKelvin); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static ThermalConductivity From(double value, ThermalConductivityUnit fro public static ThermalConductivity From(QuantityValue value, ThermalConductivityUnit fromUnit) #endif { - switch (fromUnit) - { - case ThermalConductivityUnit.WattPerMeterKelvin: - return FromWattsPerMeterKelvin(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ThermalConductivity((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static ThermalConductivity From(QuantityValue value, ThermalConductivityU { return null; } - switch (fromUnit) - { - case ThermalConductivityUnit.WattPerMeterKelvin: - return FromWattsPerMeterKelvin(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ThermalConductivity((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(ThermalConductivityUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ThermalConductivityUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ThermalConductivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(ThermalConductivityUnit unit, [CanBeNull] C #if !WINDOWS_UWP public static ThermalConductivity operator -(ThermalConductivity right) { - return new ThermalConductivity(-right._wattsPerMeterKelvin); + return new ThermalConductivity(-right.Value, right.Unit); } public static ThermalConductivity operator +(ThermalConductivity left, ThermalConductivity right) { - return new ThermalConductivity(left._wattsPerMeterKelvin + right._wattsPerMeterKelvin); + return new ThermalConductivity(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ThermalConductivity operator -(ThermalConductivity left, ThermalConductivity right) { - return new ThermalConductivity(left._wattsPerMeterKelvin - right._wattsPerMeterKelvin); + return new ThermalConductivity(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ThermalConductivity operator *(double left, ThermalConductivity right) { - return new ThermalConductivity(left*right._wattsPerMeterKelvin); + return new ThermalConductivity(left * right.Value, right.Unit); } public static ThermalConductivity operator *(ThermalConductivity left, double right) { - return new ThermalConductivity(left._wattsPerMeterKelvin*(double)right); + return new ThermalConductivity(left.Value * right, left.Unit); } public static ThermalConductivity operator /(ThermalConductivity left, double right) { - return new ThermalConductivity(left._wattsPerMeterKelvin/(double)right); + return new ThermalConductivity(left.Value / right, left.Unit); } public static double operator /(ThermalConductivity left, ThermalConductivity right) { - return Convert.ToDouble(left._wattsPerMeterKelvin/right._wattsPerMeterKelvin); + return left.WattsPerMeterKelvin / right.WattsPerMeterKelvin; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(ThermalConductivity other) { - return _wattsPerMeterKelvin.CompareTo(other._wattsPerMeterKelvin); + return AsBaseUnitWattsPerMeterKelvin().CompareTo(other.AsBaseUnitWattsPerMeterKelvin()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ThermalConductivity left, ThermalConductivity right) { - return left._wattsPerMeterKelvin <= right._wattsPerMeterKelvin; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ThermalConductivity left, ThermalConductivity right) { - return left._wattsPerMeterKelvin >= right._wattsPerMeterKelvin; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ThermalConductivity left, ThermalConductivity right) { - return left._wattsPerMeterKelvin < right._wattsPerMeterKelvin; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ThermalConductivity left, ThermalConductivity right) { - return left._wattsPerMeterKelvin > right._wattsPerMeterKelvin; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ThermalConductivity left, ThermalConductivity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._wattsPerMeterKelvin == right._wattsPerMeterKelvin; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ThermalConductivity left, ThermalConductivity right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._wattsPerMeterKelvin != right._wattsPerMeterKelvin; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _wattsPerMeterKelvin.Equals(((ThermalConductivity) obj)._wattsPerMeterKelvin); + return AsBaseUnitWattsPerMeterKelvin().Equals(((ThermalConductivity) obj).AsBaseUnitWattsPerMeterKelvin()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ThermalConductivity other, ThermalConductivity maxError) { - return Math.Abs(_wattsPerMeterKelvin - other._wattsPerMeterKelvin) <= maxError._wattsPerMeterKelvin; + return Math.Abs(AsBaseUnitWattsPerMeterKelvin() - other.AsBaseUnitWattsPerMeterKelvin()) <= maxError.AsBaseUnitWattsPerMeterKelvin(); } public override int GetHashCode() { - return _wattsPerMeterKelvin.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ThermalConductivityUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitWattsPerMeterKelvin(); + switch (unit) { - case ThermalConductivityUnit.WattPerMeterKelvin: - return WattsPerMeterKelvin; + case ThermalConductivityUnit.WattPerMeterKelvin: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static ThermalConductivity Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static ThermalConductivity Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ThermalConductivity Parse(string str, [CanBeNull] Culture culture) + public static ThermalConductivity Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out ThermalConductivity resu /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ThermalConductivity result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ThermalConductivity result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static ThermalConductivityUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ThermalConductivityUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static ThermalConductivityUnit ParseUnit(string str, [CanBeNull] string c /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static ThermalConductivityUnit ParseUnit(string str, [CanBeNull] string c #else public #endif - static ThermalConductivityUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ThermalConductivityUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ThermalConductivityUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ThermalConductivityUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static ThermalConductivityUnit ParseUnit(string str, IFormatProvider formatProvi #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is WattPerMeterKelvin /// @@ -587,7 +662,7 @@ static ThermalConductivityUnit ParseUnit(string str, IFormatProvider formatProvi /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(ThermalConductivityUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ThermalConductivityUnit unit, [CanBeNull] Culture culture) + public string ToString( + ThermalConductivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ThermalConductivityUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ThermalConductivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ThermalConductivityUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ThermalConductivityUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ThermalConductivity /// - public static ThermalConductivity MaxValue - { - get - { - return new ThermalConductivity(double.MaxValue); - } - } + public static ThermalConductivity MaxValue => new ThermalConductivity(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ThermalConductivity /// - public static ThermalConductivity MinValue + public static ThermalConductivity MinValue => new ThermalConductivity(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitWattsPerMeterKelvin() { - get + if (Unit == ThermalConductivityUnit.WattPerMeterKelvin) { return _value; } + + switch (Unit) { - return new ThermalConductivity(double.MinValue); - } - } - } + case ThermalConductivityUnit.WattPerMeterKelvin: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ThermalConductivityUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs index 2d3728b3a3..cde0cdc419 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct ThermalResistance : IComparable, IComparable - /// Base unit of ThermalResistance. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly ThermalResistanceUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _squareMeterKelvinsPerKilowatt; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public ThermalResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public ThermalResistance() : this(0) + public ThermalResistance() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public ThermalResistance(double squaremeterkelvinsperkilowatt) { - _squareMeterKelvinsPerKilowatt = Convert.ToDouble(squaremeterkelvinsperkilowatt); + _value = Convert.ToDouble(squaremeterkelvinsperkilowatt); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + ThermalResistance(double numericValue, ThermalResistanceUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit SquareMeterKelvinPerKilowatt. + /// + /// Value assuming base unit SquareMeterKelvinPerKilowatt. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ThermalResistance(long squaremeterkelvinsperkilowatt) - { - _squareMeterKelvinsPerKilowatt = Convert.ToDouble(squaremeterkelvinsperkilowatt); - } + ThermalResistance(long squaremeterkelvinsperkilowatt) : this(Convert.ToDouble(squaremeterkelvinsperkilowatt), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit SquareMeterKelvinPerKilowatt. + /// + /// Value assuming base unit SquareMeterKelvinPerKilowatt. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - ThermalResistance(decimal squaremeterkelvinsperkilowatt) - { - _squareMeterKelvinsPerKilowatt = Convert.ToDouble(squaremeterkelvinsperkilowatt); - } + ThermalResistance(decimal squaremeterkelvinsperkilowatt) : this(Convert.ToDouble(squaremeterkelvinsperkilowatt), BaseUnit) { } #region Properties @@ -119,64 +156,38 @@ public ThermalResistance(double squaremeterkelvinsperkilowatt) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static ThermalResistanceUnit BaseUnit - { - get { return ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; } - } + public static ThermalResistanceUnit BaseUnit => ThermalResistanceUnit.SquareMeterKelvinPerKilowatt; /// /// All units of measurement for the ThermalResistance quantity. /// public static ThermalResistanceUnit[] Units { get; } = Enum.GetValues(typeof(ThermalResistanceUnit)).Cast().ToArray(); - /// /// Get ThermalResistance in HourSquareFeetDegreesFahrenheitPerBtu. /// - public double HourSquareFeetDegreesFahrenheitPerBtu - { - get { return _squareMeterKelvinsPerKilowatt/176.1121482159839; } - } - + public double HourSquareFeetDegreesFahrenheitPerBtu => As(ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); /// /// Get ThermalResistance in SquareCentimeterHourDegreesCelsiusPerKilocalorie. /// - public double SquareCentimeterHourDegreesCelsiusPerKilocalorie - { - get { return _squareMeterKelvinsPerKilowatt/0.0859779507590433; } - } - + public double SquareCentimeterHourDegreesCelsiusPerKilocalorie => As(ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); /// /// Get ThermalResistance in SquareCentimeterKelvinsPerWatt. /// - public double SquareCentimeterKelvinsPerWatt - { - get { return _squareMeterKelvinsPerKilowatt/0.0999964777570357; } - } - + public double SquareCentimeterKelvinsPerWatt => As(ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); /// /// Get ThermalResistance in SquareMeterDegreesCelsiusPerWatt. /// - public double SquareMeterDegreesCelsiusPerWatt - { - get { return _squareMeterKelvinsPerKilowatt/1000.088056074108; } - } - + public double SquareMeterDegreesCelsiusPerWatt => As(ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); /// /// Get ThermalResistance in SquareMeterKelvinsPerKilowatt. /// - public double SquareMeterKelvinsPerKilowatt - { - get { return _squareMeterKelvinsPerKilowatt; } - } + public double SquareMeterKelvinsPerKilowatt => As(ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); #endregion #region Static - public static ThermalResistance Zero - { - get { return new ThermalResistance(); } - } + public static ThermalResistance Zero => new ThermalResistance(0, BaseUnit); /// /// Get ThermalResistance from HourSquareFeetDegreesFahrenheitPerBtu. @@ -184,17 +195,13 @@ public static ThermalResistance Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(double hoursquarefeetdegreesfahrenheitperbtu) - { - double value = (double) hoursquarefeetdegreesfahrenheitperbtu; - return new ThermalResistance(value*176.1121482159839); - } #else public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(QuantityValue hoursquarefeetdegreesfahrenheitperbtu) +#endif { double value = (double) hoursquarefeetdegreesfahrenheitperbtu; - return new ThermalResistance((value*176.1121482159839)); + return new ThermalResistance(value, ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); } -#endif /// /// Get ThermalResistance from SquareCentimeterHourDegreesCelsiusPerKilocalorie. @@ -202,17 +209,13 @@ public static ThermalResistance FromHourSquareFeetDegreesFahrenheitPerBtu(Quanti #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(double squarecentimeterhourdegreescelsiusperkilocalorie) - { - double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; - return new ThermalResistance(value*0.0859779507590433); - } #else public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(QuantityValue squarecentimeterhourdegreescelsiusperkilocalorie) +#endif { double value = (double) squarecentimeterhourdegreescelsiusperkilocalorie; - return new ThermalResistance((value*0.0859779507590433)); + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); } -#endif /// /// Get ThermalResistance from SquareCentimeterKelvinsPerWatt. @@ -220,17 +223,13 @@ public static ThermalResistance FromSquareCentimeterHourDegreesCelsiusPerKilocal #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(double squarecentimeterkelvinsperwatt) - { - double value = (double) squarecentimeterkelvinsperwatt; - return new ThermalResistance(value*0.0999964777570357); - } #else public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(QuantityValue squarecentimeterkelvinsperwatt) +#endif { double value = (double) squarecentimeterkelvinsperwatt; - return new ThermalResistance((value*0.0999964777570357)); + return new ThermalResistance(value, ThermalResistanceUnit.SquareCentimeterKelvinPerWatt); } -#endif /// /// Get ThermalResistance from SquareMeterDegreesCelsiusPerWatt. @@ -238,17 +237,13 @@ public static ThermalResistance FromSquareCentimeterKelvinsPerWatt(QuantityValue #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(double squaremeterdegreescelsiusperwatt) - { - double value = (double) squaremeterdegreescelsiusperwatt; - return new ThermalResistance(value*1000.088056074108); - } #else public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(QuantityValue squaremeterdegreescelsiusperwatt) +#endif { double value = (double) squaremeterdegreescelsiusperwatt; - return new ThermalResistance((value*1000.088056074108)); + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt); } -#endif /// /// Get ThermalResistance from SquareMeterKelvinsPerKilowatt. @@ -256,17 +251,13 @@ public static ThermalResistance FromSquareMeterDegreesCelsiusPerWatt(QuantityVal #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(double squaremeterkelvinsperkilowatt) - { - double value = (double) squaremeterkelvinsperkilowatt; - return new ThermalResistance(value); - } #else public static ThermalResistance FromSquareMeterKelvinsPerKilowatt(QuantityValue squaremeterkelvinsperkilowatt) +#endif { double value = (double) squaremeterkelvinsperkilowatt; - return new ThermalResistance((value)); + return new ThermalResistance(value, ThermalResistanceUnit.SquareMeterKelvinPerKilowatt); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -361,22 +352,7 @@ public static ThermalResistance From(double value, ThermalResistanceUnit fromUni public static ThermalResistance From(QuantityValue value, ThermalResistanceUnit fromUnit) #endif { - switch (fromUnit) - { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: - return FromHourSquareFeetDegreesFahrenheitPerBtu(value); - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: - return FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(value); - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: - return FromSquareCentimeterKelvinsPerWatt(value); - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: - return FromSquareMeterDegreesCelsiusPerWatt(value); - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: - return FromSquareMeterKelvinsPerKilowatt(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ThermalResistance((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -393,22 +369,8 @@ public static ThermalResistance From(QuantityValue value, ThermalResistanceUnit { return null; } - switch (fromUnit) - { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: - return FromHourSquareFeetDegreesFahrenheitPerBtu(value.Value); - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: - return FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(value.Value); - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: - return FromSquareCentimeterKelvinsPerWatt(value.Value); - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: - return FromSquareMeterDegreesCelsiusPerWatt(value.Value); - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: - return FromSquareMeterKelvinsPerKilowatt(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new ThermalResistance((double)value.Value, fromUnit); } #endif @@ -427,12 +389,29 @@ public static string GetAbbreviation(ThermalResistanceUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(ThermalResistanceUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + ThermalResistanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -443,37 +422,37 @@ public static string GetAbbreviation(ThermalResistanceUnit unit, [CanBeNull] Cul #if !WINDOWS_UWP public static ThermalResistance operator -(ThermalResistance right) { - return new ThermalResistance(-right._squareMeterKelvinsPerKilowatt); + return new ThermalResistance(-right.Value, right.Unit); } public static ThermalResistance operator +(ThermalResistance left, ThermalResistance right) { - return new ThermalResistance(left._squareMeterKelvinsPerKilowatt + right._squareMeterKelvinsPerKilowatt); + return new ThermalResistance(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static ThermalResistance operator -(ThermalResistance left, ThermalResistance right) { - return new ThermalResistance(left._squareMeterKelvinsPerKilowatt - right._squareMeterKelvinsPerKilowatt); + return new ThermalResistance(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static ThermalResistance operator *(double left, ThermalResistance right) { - return new ThermalResistance(left*right._squareMeterKelvinsPerKilowatt); + return new ThermalResistance(left * right.Value, right.Unit); } public static ThermalResistance operator *(ThermalResistance left, double right) { - return new ThermalResistance(left._squareMeterKelvinsPerKilowatt*(double)right); + return new ThermalResistance(left.Value * right, left.Unit); } public static ThermalResistance operator /(ThermalResistance left, double right) { - return new ThermalResistance(left._squareMeterKelvinsPerKilowatt/(double)right); + return new ThermalResistance(left.Value / right, left.Unit); } public static double operator /(ThermalResistance left, ThermalResistance right) { - return Convert.ToDouble(left._squareMeterKelvinsPerKilowatt/right._squareMeterKelvinsPerKilowatt); + return left.SquareMeterKelvinsPerKilowatt / right.SquareMeterKelvinsPerKilowatt; } #endif @@ -496,43 +475,43 @@ public int CompareTo(object obj) #endif int CompareTo(ThermalResistance other) { - return _squareMeterKelvinsPerKilowatt.CompareTo(other._squareMeterKelvinsPerKilowatt); + return AsBaseUnitSquareMeterKelvinsPerKilowatt().CompareTo(other.AsBaseUnitSquareMeterKelvinsPerKilowatt()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(ThermalResistance left, ThermalResistance right) { - return left._squareMeterKelvinsPerKilowatt <= right._squareMeterKelvinsPerKilowatt; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(ThermalResistance left, ThermalResistance right) { - return left._squareMeterKelvinsPerKilowatt >= right._squareMeterKelvinsPerKilowatt; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(ThermalResistance left, ThermalResistance right) { - return left._squareMeterKelvinsPerKilowatt < right._squareMeterKelvinsPerKilowatt; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(ThermalResistance left, ThermalResistance right) { - return left._squareMeterKelvinsPerKilowatt > right._squareMeterKelvinsPerKilowatt; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(ThermalResistance left, ThermalResistance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._squareMeterKelvinsPerKilowatt == right._squareMeterKelvinsPerKilowatt; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(ThermalResistance left, ThermalResistance right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._squareMeterKelvinsPerKilowatt != right._squareMeterKelvinsPerKilowatt; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -544,7 +523,7 @@ public override bool Equals(object obj) return false; } - return _squareMeterKelvinsPerKilowatt.Equals(((ThermalResistance) obj)._squareMeterKelvinsPerKilowatt); + return AsBaseUnitSquareMeterKelvinsPerKilowatt().Equals(((ThermalResistance) obj).AsBaseUnitSquareMeterKelvinsPerKilowatt()); } /// @@ -557,12 +536,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(ThermalResistance other, ThermalResistance maxError) { - return Math.Abs(_squareMeterKelvinsPerKilowatt - other._squareMeterKelvinsPerKilowatt) <= maxError._squareMeterKelvinsPerKilowatt; + return Math.Abs(AsBaseUnitSquareMeterKelvinsPerKilowatt() - other.AsBaseUnitSquareMeterKelvinsPerKilowatt()) <= maxError.AsBaseUnitSquareMeterKelvinsPerKilowatt(); } public override int GetHashCode() { - return _squareMeterKelvinsPerKilowatt.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -572,22 +551,23 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(ThermalResistanceUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitSquareMeterKelvinsPerKilowatt(); + switch (unit) { - case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: - return HourSquareFeetDegreesFahrenheitPerBtu; - case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: - return SquareCentimeterHourDegreesCelsiusPerKilocalorie; - case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: - return SquareCentimeterKelvinsPerWatt; - case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: - return SquareMeterDegreesCelsiusPerWatt; - case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: - return SquareMeterKelvinsPerKilowatt; + case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return baseUnitValue/176.1121482159839; + case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return baseUnitValue/0.0859779507590433; + case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return baseUnitValue/0.0999964777570357; + case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return baseUnitValue/1000.088056074108; + case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -629,7 +609,11 @@ public static ThermalResistance Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -648,17 +632,24 @@ public static ThermalResistance Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static ThermalResistance Parse(string str, [CanBeNull] Culture culture) + public static ThermalResistance Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -684,16 +675,41 @@ public static bool TryParse([CanBeNull] string str, out ThermalResistance result /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out ThermalResistance result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out ThermalResistance result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -706,6 +722,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -719,11 +736,14 @@ public static ThermalResistanceUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static ThermalResistanceUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -732,6 +752,8 @@ public static ThermalResistanceUnit ParseUnit(string str, [CanBeNull] string cul /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -744,18 +766,18 @@ public static ThermalResistanceUnit ParseUnit(string str, [CanBeNull] string cul #else public #endif - static ThermalResistanceUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static ThermalResistanceUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == ThermalResistanceUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized ThermalResistanceUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -764,6 +786,7 @@ static ThermalResistanceUnit ParseUnit(string str, IFormatProvider formatProvide #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is SquareMeterKelvinPerKilowatt /// @@ -775,7 +798,7 @@ static ThermalResistanceUnit ParseUnit(string str, IFormatProvider formatProvide /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -792,74 +815,133 @@ public string ToString(ThermalResistanceUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(ThermalResistanceUnit unit, [CanBeNull] Culture culture) + public string ToString( + ThermalResistanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(ThermalResistanceUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + ThermalResistanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(ThermalResistanceUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + ThermalResistanceUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of ThermalResistance /// - public static ThermalResistance MaxValue - { - get - { - return new ThermalResistance(double.MaxValue); - } - } + public static ThermalResistance MaxValue => new ThermalResistance(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of ThermalResistance /// - public static ThermalResistance MinValue + public static ThermalResistance MinValue => new ThermalResistance(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitSquareMeterKelvinsPerKilowatt() { - get + if (Unit == ThermalResistanceUnit.SquareMeterKelvinPerKilowatt) { return _value; } + + switch (Unit) { - return new ThermalResistance(double.MinValue); - } - } - } + case ThermalResistanceUnit.HourSquareFeetDegreeFahrenheitPerBtu: return _value*176.1121482159839; + case ThermalResistanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie: return _value*0.0859779507590433; + case ThermalResistanceUnit.SquareCentimeterKelvinPerWatt: return _value*0.0999964777570357; + case ThermalResistanceUnit.SquareMeterDegreeCelsiusPerWatt: return _value*1000.088056074108; + case ThermalResistanceUnit.SquareMeterKelvinPerKilowatt: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(ThermalResistanceUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs index f19a153070..225ff84c21 100644 --- a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Torque : IComparable, IComparable #endif { /// - /// Base unit of Torque. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly TorqueUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _newtonMeters; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Torque() : this(0) + public Torque() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Torque(double newtonmeters) { - _newtonMeters = Convert.ToDouble(newtonmeters); + _value = Convert.ToDouble(newtonmeters); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Torque(double numericValue, TorqueUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit NewtonMeter. + /// + /// Value assuming base unit NewtonMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Torque(long newtonmeters) - { - _newtonMeters = Convert.ToDouble(newtonmeters); - } + Torque(long newtonmeters) : this(Convert.ToDouble(newtonmeters), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit NewtonMeter. + /// + /// Value assuming base unit NewtonMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Torque(decimal newtonmeters) - { - _newtonMeters = Convert.ToDouble(newtonmeters); - } + Torque(decimal newtonmeters) : this(Convert.ToDouble(newtonmeters), BaseUnit) { } #region Properties @@ -119,192 +156,102 @@ public Torque(double newtonmeters) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static TorqueUnit BaseUnit - { - get { return TorqueUnit.NewtonMeter; } - } + public static TorqueUnit BaseUnit => TorqueUnit.NewtonMeter; /// /// All units of measurement for the Torque quantity. /// public static TorqueUnit[] Units { get; } = Enum.GetValues(typeof(TorqueUnit)).Cast().ToArray(); - /// /// Get Torque in KilogramForceCentimeters. /// - public double KilogramForceCentimeters - { - get { return _newtonMeters*10.1971619222242; } - } - + public double KilogramForceCentimeters => As(TorqueUnit.KilogramForceCentimeter); /// /// Get Torque in KilogramForceMeters. /// - public double KilogramForceMeters - { - get { return _newtonMeters*0.101971619222242; } - } - + public double KilogramForceMeters => As(TorqueUnit.KilogramForceMeter); /// /// Get Torque in KilogramForceMillimeters. /// - public double KilogramForceMillimeters - { - get { return _newtonMeters*101.971619222242; } - } - + public double KilogramForceMillimeters => As(TorqueUnit.KilogramForceMillimeter); /// /// Get Torque in KilonewtonCentimeters. /// - public double KilonewtonCentimeters - { - get { return (_newtonMeters*100) / 1e3d; } - } - + public double KilonewtonCentimeters => As(TorqueUnit.KilonewtonCentimeter); /// /// Get Torque in KilonewtonMeters. /// - public double KilonewtonMeters - { - get { return (_newtonMeters) / 1e3d; } - } - + public double KilonewtonMeters => As(TorqueUnit.KilonewtonMeter); /// /// Get Torque in KilonewtonMillimeters. /// - public double KilonewtonMillimeters - { - get { return (_newtonMeters*1000) / 1e3d; } - } - + public double KilonewtonMillimeters => As(TorqueUnit.KilonewtonMillimeter); /// /// Get Torque in KilopoundForceFeet. /// - public double KilopoundForceFeet - { - get { return (_newtonMeters*0.737562085483396) / 1e3d; } - } - + public double KilopoundForceFeet => As(TorqueUnit.KilopoundForceFoot); /// /// Get Torque in KilopoundForceInches. /// - public double KilopoundForceInches - { - get { return (_newtonMeters*8.85074502580075) / 1e3d; } - } - + public double KilopoundForceInches => As(TorqueUnit.KilopoundForceInch); /// /// Get Torque in MeganewtonCentimeters. /// - public double MeganewtonCentimeters - { - get { return (_newtonMeters*100) / 1e6d; } - } - + public double MeganewtonCentimeters => As(TorqueUnit.MeganewtonCentimeter); /// /// Get Torque in MeganewtonMeters. /// - public double MeganewtonMeters - { - get { return (_newtonMeters) / 1e6d; } - } - + public double MeganewtonMeters => As(TorqueUnit.MeganewtonMeter); /// /// Get Torque in MeganewtonMillimeters. /// - public double MeganewtonMillimeters - { - get { return (_newtonMeters*1000) / 1e6d; } - } - + public double MeganewtonMillimeters => As(TorqueUnit.MeganewtonMillimeter); /// /// Get Torque in MegapoundForceFeet. /// - public double MegapoundForceFeet - { - get { return (_newtonMeters*0.737562085483396) / 1e6d; } - } - + public double MegapoundForceFeet => As(TorqueUnit.MegapoundForceFoot); /// /// Get Torque in MegapoundForceInches. /// - public double MegapoundForceInches - { - get { return (_newtonMeters*8.85074502580075) / 1e6d; } - } - + public double MegapoundForceInches => As(TorqueUnit.MegapoundForceInch); /// /// Get Torque in NewtonCentimeters. /// - public double NewtonCentimeters - { - get { return _newtonMeters*100; } - } - + public double NewtonCentimeters => As(TorqueUnit.NewtonCentimeter); /// /// Get Torque in NewtonMeters. /// - public double NewtonMeters - { - get { return _newtonMeters; } - } - + public double NewtonMeters => As(TorqueUnit.NewtonMeter); /// /// Get Torque in NewtonMillimeters. /// - public double NewtonMillimeters - { - get { return _newtonMeters*1000; } - } - + public double NewtonMillimeters => As(TorqueUnit.NewtonMillimeter); /// /// Get Torque in PoundForceFeet. /// - public double PoundForceFeet - { - get { return _newtonMeters*0.737562085483396; } - } - + public double PoundForceFeet => As(TorqueUnit.PoundForceFoot); /// /// Get Torque in PoundForceInches. /// - public double PoundForceInches - { - get { return _newtonMeters*8.85074502580075; } - } - + public double PoundForceInches => As(TorqueUnit.PoundForceInch); /// /// Get Torque in TonneForceCentimeters. /// - public double TonneForceCentimeters - { - get { return _newtonMeters*0.0101971619222242; } - } - + public double TonneForceCentimeters => As(TorqueUnit.TonneForceCentimeter); /// /// Get Torque in TonneForceMeters. /// - public double TonneForceMeters - { - get { return _newtonMeters*0.000101971619222242; } - } - + public double TonneForceMeters => As(TorqueUnit.TonneForceMeter); /// /// Get Torque in TonneForceMillimeters. /// - public double TonneForceMillimeters - { - get { return _newtonMeters*0.101971619222242; } - } + public double TonneForceMillimeters => As(TorqueUnit.TonneForceMillimeter); #endregion #region Static - public static Torque Zero - { - get { return new Torque(); } - } + public static Torque Zero => new Torque(0, BaseUnit); /// /// Get Torque from KilogramForceCentimeters. @@ -312,17 +259,13 @@ public static Torque Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromKilogramForceCentimeters(double kilogramforcecentimeters) - { - double value = (double) kilogramforcecentimeters; - return new Torque(value*0.0980665019960652); - } #else public static Torque FromKilogramForceCentimeters(QuantityValue kilogramforcecentimeters) +#endif { double value = (double) kilogramforcecentimeters; - return new Torque((value*0.0980665019960652)); + return new Torque(value, TorqueUnit.KilogramForceCentimeter); } -#endif /// /// Get Torque from KilogramForceMeters. @@ -330,17 +273,13 @@ public static Torque FromKilogramForceCentimeters(QuantityValue kilogramforcecen #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromKilogramForceMeters(double kilogramforcemeters) - { - double value = (double) kilogramforcemeters; - return new Torque(value*9.80665019960652); - } #else public static Torque FromKilogramForceMeters(QuantityValue kilogramforcemeters) +#endif { double value = (double) kilogramforcemeters; - return new Torque((value*9.80665019960652)); + return new Torque(value, TorqueUnit.KilogramForceMeter); } -#endif /// /// Get Torque from KilogramForceMillimeters. @@ -348,17 +287,13 @@ public static Torque FromKilogramForceMeters(QuantityValue kilogramforcemeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromKilogramForceMillimeters(double kilogramforcemillimeters) - { - double value = (double) kilogramforcemillimeters; - return new Torque(value*0.00980665019960652); - } #else public static Torque FromKilogramForceMillimeters(QuantityValue kilogramforcemillimeters) +#endif { double value = (double) kilogramforcemillimeters; - return new Torque((value*0.00980665019960652)); + return new Torque(value, TorqueUnit.KilogramForceMillimeter); } -#endif /// /// Get Torque from KilonewtonCentimeters. @@ -366,17 +301,13 @@ public static Torque FromKilogramForceMillimeters(QuantityValue kilogramforcemil #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromKilonewtonCentimeters(double kilonewtoncentimeters) - { - double value = (double) kilonewtoncentimeters; - return new Torque((value*0.01) * 1e3d); - } #else public static Torque FromKilonewtonCentimeters(QuantityValue kilonewtoncentimeters) +#endif { double value = (double) kilonewtoncentimeters; - return new Torque(((value*0.01) * 1e3d)); + return new Torque(value, TorqueUnit.KilonewtonCentimeter); } -#endif /// /// Get Torque from KilonewtonMeters. @@ -384,17 +315,13 @@ public static Torque FromKilonewtonCentimeters(QuantityValue kilonewtoncentimete #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromKilonewtonMeters(double kilonewtonmeters) - { - double value = (double) kilonewtonmeters; - return new Torque((value) * 1e3d); - } #else public static Torque FromKilonewtonMeters(QuantityValue kilonewtonmeters) +#endif { double value = (double) kilonewtonmeters; - return new Torque(((value) * 1e3d)); + return new Torque(value, TorqueUnit.KilonewtonMeter); } -#endif /// /// Get Torque from KilonewtonMillimeters. @@ -402,17 +329,13 @@ public static Torque FromKilonewtonMeters(QuantityValue kilonewtonmeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromKilonewtonMillimeters(double kilonewtonmillimeters) - { - double value = (double) kilonewtonmillimeters; - return new Torque((value*0.001) * 1e3d); - } #else public static Torque FromKilonewtonMillimeters(QuantityValue kilonewtonmillimeters) +#endif { double value = (double) kilonewtonmillimeters; - return new Torque(((value*0.001) * 1e3d)); + return new Torque(value, TorqueUnit.KilonewtonMillimeter); } -#endif /// /// Get Torque from KilopoundForceFeet. @@ -420,17 +343,13 @@ public static Torque FromKilonewtonMillimeters(QuantityValue kilonewtonmillimete #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromKilopoundForceFeet(double kilopoundforcefeet) - { - double value = (double) kilopoundforcefeet; - return new Torque((value*1.3558180656) * 1e3d); - } #else public static Torque FromKilopoundForceFeet(QuantityValue kilopoundforcefeet) +#endif { double value = (double) kilopoundforcefeet; - return new Torque(((value*1.3558180656) * 1e3d)); + return new Torque(value, TorqueUnit.KilopoundForceFoot); } -#endif /// /// Get Torque from KilopoundForceInches. @@ -438,17 +357,13 @@ public static Torque FromKilopoundForceFeet(QuantityValue kilopoundforcefeet) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromKilopoundForceInches(double kilopoundforceinches) - { - double value = (double) kilopoundforceinches; - return new Torque((value*0.1129848388) * 1e3d); - } #else public static Torque FromKilopoundForceInches(QuantityValue kilopoundforceinches) +#endif { double value = (double) kilopoundforceinches; - return new Torque(((value*0.1129848388) * 1e3d)); + return new Torque(value, TorqueUnit.KilopoundForceInch); } -#endif /// /// Get Torque from MeganewtonCentimeters. @@ -456,17 +371,13 @@ public static Torque FromKilopoundForceInches(QuantityValue kilopoundforceinches #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromMeganewtonCentimeters(double meganewtoncentimeters) - { - double value = (double) meganewtoncentimeters; - return new Torque((value*0.01) * 1e6d); - } #else public static Torque FromMeganewtonCentimeters(QuantityValue meganewtoncentimeters) +#endif { double value = (double) meganewtoncentimeters; - return new Torque(((value*0.01) * 1e6d)); + return new Torque(value, TorqueUnit.MeganewtonCentimeter); } -#endif /// /// Get Torque from MeganewtonMeters. @@ -474,17 +385,13 @@ public static Torque FromMeganewtonCentimeters(QuantityValue meganewtoncentimete #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromMeganewtonMeters(double meganewtonmeters) - { - double value = (double) meganewtonmeters; - return new Torque((value) * 1e6d); - } #else public static Torque FromMeganewtonMeters(QuantityValue meganewtonmeters) +#endif { double value = (double) meganewtonmeters; - return new Torque(((value) * 1e6d)); + return new Torque(value, TorqueUnit.MeganewtonMeter); } -#endif /// /// Get Torque from MeganewtonMillimeters. @@ -492,17 +399,13 @@ public static Torque FromMeganewtonMeters(QuantityValue meganewtonmeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromMeganewtonMillimeters(double meganewtonmillimeters) - { - double value = (double) meganewtonmillimeters; - return new Torque((value*0.001) * 1e6d); - } #else public static Torque FromMeganewtonMillimeters(QuantityValue meganewtonmillimeters) +#endif { double value = (double) meganewtonmillimeters; - return new Torque(((value*0.001) * 1e6d)); + return new Torque(value, TorqueUnit.MeganewtonMillimeter); } -#endif /// /// Get Torque from MegapoundForceFeet. @@ -510,17 +413,13 @@ public static Torque FromMeganewtonMillimeters(QuantityValue meganewtonmillimete #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromMegapoundForceFeet(double megapoundforcefeet) - { - double value = (double) megapoundforcefeet; - return new Torque((value*1.3558180656) * 1e6d); - } #else public static Torque FromMegapoundForceFeet(QuantityValue megapoundforcefeet) +#endif { double value = (double) megapoundforcefeet; - return new Torque(((value*1.3558180656) * 1e6d)); + return new Torque(value, TorqueUnit.MegapoundForceFoot); } -#endif /// /// Get Torque from MegapoundForceInches. @@ -528,17 +427,13 @@ public static Torque FromMegapoundForceFeet(QuantityValue megapoundforcefeet) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromMegapoundForceInches(double megapoundforceinches) - { - double value = (double) megapoundforceinches; - return new Torque((value*0.1129848388) * 1e6d); - } #else public static Torque FromMegapoundForceInches(QuantityValue megapoundforceinches) +#endif { double value = (double) megapoundforceinches; - return new Torque(((value*0.1129848388) * 1e6d)); + return new Torque(value, TorqueUnit.MegapoundForceInch); } -#endif /// /// Get Torque from NewtonCentimeters. @@ -546,17 +441,13 @@ public static Torque FromMegapoundForceInches(QuantityValue megapoundforceinches #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromNewtonCentimeters(double newtoncentimeters) - { - double value = (double) newtoncentimeters; - return new Torque(value*0.01); - } #else public static Torque FromNewtonCentimeters(QuantityValue newtoncentimeters) +#endif { double value = (double) newtoncentimeters; - return new Torque((value*0.01)); + return new Torque(value, TorqueUnit.NewtonCentimeter); } -#endif /// /// Get Torque from NewtonMeters. @@ -564,17 +455,13 @@ public static Torque FromNewtonCentimeters(QuantityValue newtoncentimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromNewtonMeters(double newtonmeters) - { - double value = (double) newtonmeters; - return new Torque(value); - } #else public static Torque FromNewtonMeters(QuantityValue newtonmeters) +#endif { double value = (double) newtonmeters; - return new Torque((value)); + return new Torque(value, TorqueUnit.NewtonMeter); } -#endif /// /// Get Torque from NewtonMillimeters. @@ -582,17 +469,13 @@ public static Torque FromNewtonMeters(QuantityValue newtonmeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromNewtonMillimeters(double newtonmillimeters) - { - double value = (double) newtonmillimeters; - return new Torque(value*0.001); - } #else public static Torque FromNewtonMillimeters(QuantityValue newtonmillimeters) +#endif { double value = (double) newtonmillimeters; - return new Torque((value*0.001)); + return new Torque(value, TorqueUnit.NewtonMillimeter); } -#endif /// /// Get Torque from PoundForceFeet. @@ -600,17 +483,13 @@ public static Torque FromNewtonMillimeters(QuantityValue newtonmillimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromPoundForceFeet(double poundforcefeet) - { - double value = (double) poundforcefeet; - return new Torque(value*1.3558180656); - } #else public static Torque FromPoundForceFeet(QuantityValue poundforcefeet) +#endif { double value = (double) poundforcefeet; - return new Torque((value*1.3558180656)); + return new Torque(value, TorqueUnit.PoundForceFoot); } -#endif /// /// Get Torque from PoundForceInches. @@ -618,17 +497,13 @@ public static Torque FromPoundForceFeet(QuantityValue poundforcefeet) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromPoundForceInches(double poundforceinches) - { - double value = (double) poundforceinches; - return new Torque(value*0.1129848388); - } #else public static Torque FromPoundForceInches(QuantityValue poundforceinches) +#endif { double value = (double) poundforceinches; - return new Torque((value*0.1129848388)); + return new Torque(value, TorqueUnit.PoundForceInch); } -#endif /// /// Get Torque from TonneForceCentimeters. @@ -636,17 +511,13 @@ public static Torque FromPoundForceInches(QuantityValue poundforceinches) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromTonneForceCentimeters(double tonneforcecentimeters) - { - double value = (double) tonneforcecentimeters; - return new Torque(value*98.0665019960652); - } #else public static Torque FromTonneForceCentimeters(QuantityValue tonneforcecentimeters) +#endif { double value = (double) tonneforcecentimeters; - return new Torque((value*98.0665019960652)); + return new Torque(value, TorqueUnit.TonneForceCentimeter); } -#endif /// /// Get Torque from TonneForceMeters. @@ -654,17 +525,13 @@ public static Torque FromTonneForceCentimeters(QuantityValue tonneforcecentimete #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromTonneForceMeters(double tonneforcemeters) - { - double value = (double) tonneforcemeters; - return new Torque(value*9806.65019960653); - } #else public static Torque FromTonneForceMeters(QuantityValue tonneforcemeters) +#endif { double value = (double) tonneforcemeters; - return new Torque((value*9806.65019960653)); + return new Torque(value, TorqueUnit.TonneForceMeter); } -#endif /// /// Get Torque from TonneForceMillimeters. @@ -672,17 +539,13 @@ public static Torque FromTonneForceMeters(QuantityValue tonneforcemeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Torque FromTonneForceMillimeters(double tonneforcemillimeters) - { - double value = (double) tonneforcemillimeters; - return new Torque(value*9.80665019960652); - } #else public static Torque FromTonneForceMillimeters(QuantityValue tonneforcemillimeters) +#endif { double value = (double) tonneforcemillimeters; - return new Torque((value*9.80665019960652)); + return new Torque(value, TorqueUnit.TonneForceMillimeter); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1017,54 +880,7 @@ public static Torque From(double value, TorqueUnit fromUnit) public static Torque From(QuantityValue value, TorqueUnit fromUnit) #endif { - switch (fromUnit) - { - case TorqueUnit.KilogramForceCentimeter: - return FromKilogramForceCentimeters(value); - case TorqueUnit.KilogramForceMeter: - return FromKilogramForceMeters(value); - case TorqueUnit.KilogramForceMillimeter: - return FromKilogramForceMillimeters(value); - case TorqueUnit.KilonewtonCentimeter: - return FromKilonewtonCentimeters(value); - case TorqueUnit.KilonewtonMeter: - return FromKilonewtonMeters(value); - case TorqueUnit.KilonewtonMillimeter: - return FromKilonewtonMillimeters(value); - case TorqueUnit.KilopoundForceFoot: - return FromKilopoundForceFeet(value); - case TorqueUnit.KilopoundForceInch: - return FromKilopoundForceInches(value); - case TorqueUnit.MeganewtonCentimeter: - return FromMeganewtonCentimeters(value); - case TorqueUnit.MeganewtonMeter: - return FromMeganewtonMeters(value); - case TorqueUnit.MeganewtonMillimeter: - return FromMeganewtonMillimeters(value); - case TorqueUnit.MegapoundForceFoot: - return FromMegapoundForceFeet(value); - case TorqueUnit.MegapoundForceInch: - return FromMegapoundForceInches(value); - case TorqueUnit.NewtonCentimeter: - return FromNewtonCentimeters(value); - case TorqueUnit.NewtonMeter: - return FromNewtonMeters(value); - case TorqueUnit.NewtonMillimeter: - return FromNewtonMillimeters(value); - case TorqueUnit.PoundForceFoot: - return FromPoundForceFeet(value); - case TorqueUnit.PoundForceInch: - return FromPoundForceInches(value); - case TorqueUnit.TonneForceCentimeter: - return FromTonneForceCentimeters(value); - case TorqueUnit.TonneForceMeter: - return FromTonneForceMeters(value); - case TorqueUnit.TonneForceMillimeter: - return FromTonneForceMillimeters(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Torque((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1081,54 +897,8 @@ public static Torque From(QuantityValue value, TorqueUnit fromUnit) { return null; } - switch (fromUnit) - { - case TorqueUnit.KilogramForceCentimeter: - return FromKilogramForceCentimeters(value.Value); - case TorqueUnit.KilogramForceMeter: - return FromKilogramForceMeters(value.Value); - case TorqueUnit.KilogramForceMillimeter: - return FromKilogramForceMillimeters(value.Value); - case TorqueUnit.KilonewtonCentimeter: - return FromKilonewtonCentimeters(value.Value); - case TorqueUnit.KilonewtonMeter: - return FromKilonewtonMeters(value.Value); - case TorqueUnit.KilonewtonMillimeter: - return FromKilonewtonMillimeters(value.Value); - case TorqueUnit.KilopoundForceFoot: - return FromKilopoundForceFeet(value.Value); - case TorqueUnit.KilopoundForceInch: - return FromKilopoundForceInches(value.Value); - case TorqueUnit.MeganewtonCentimeter: - return FromMeganewtonCentimeters(value.Value); - case TorqueUnit.MeganewtonMeter: - return FromMeganewtonMeters(value.Value); - case TorqueUnit.MeganewtonMillimeter: - return FromMeganewtonMillimeters(value.Value); - case TorqueUnit.MegapoundForceFoot: - return FromMegapoundForceFeet(value.Value); - case TorqueUnit.MegapoundForceInch: - return FromMegapoundForceInches(value.Value); - case TorqueUnit.NewtonCentimeter: - return FromNewtonCentimeters(value.Value); - case TorqueUnit.NewtonMeter: - return FromNewtonMeters(value.Value); - case TorqueUnit.NewtonMillimeter: - return FromNewtonMillimeters(value.Value); - case TorqueUnit.PoundForceFoot: - return FromPoundForceFeet(value.Value); - case TorqueUnit.PoundForceInch: - return FromPoundForceInches(value.Value); - case TorqueUnit.TonneForceCentimeter: - return FromTonneForceCentimeters(value.Value); - case TorqueUnit.TonneForceMeter: - return FromTonneForceMeters(value.Value); - case TorqueUnit.TonneForceMillimeter: - return FromTonneForceMillimeters(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Torque((double)value.Value, fromUnit); } #endif @@ -1147,12 +917,29 @@ public static string GetAbbreviation(TorqueUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(TorqueUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + TorqueUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1163,37 +950,37 @@ public static string GetAbbreviation(TorqueUnit unit, [CanBeNull] Culture cultur #if !WINDOWS_UWP public static Torque operator -(Torque right) { - return new Torque(-right._newtonMeters); + return new Torque(-right.Value, right.Unit); } public static Torque operator +(Torque left, Torque right) { - return new Torque(left._newtonMeters + right._newtonMeters); + return new Torque(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Torque operator -(Torque left, Torque right) { - return new Torque(left._newtonMeters - right._newtonMeters); + return new Torque(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Torque operator *(double left, Torque right) { - return new Torque(left*right._newtonMeters); + return new Torque(left * right.Value, right.Unit); } public static Torque operator *(Torque left, double right) { - return new Torque(left._newtonMeters*(double)right); + return new Torque(left.Value * right, left.Unit); } public static Torque operator /(Torque left, double right) { - return new Torque(left._newtonMeters/(double)right); + return new Torque(left.Value / right, left.Unit); } public static double operator /(Torque left, Torque right) { - return Convert.ToDouble(left._newtonMeters/right._newtonMeters); + return left.NewtonMeters / right.NewtonMeters; } #endif @@ -1216,43 +1003,43 @@ public int CompareTo(object obj) #endif int CompareTo(Torque other) { - return _newtonMeters.CompareTo(other._newtonMeters); + return AsBaseUnitNewtonMeters().CompareTo(other.AsBaseUnitNewtonMeters()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Torque left, Torque right) { - return left._newtonMeters <= right._newtonMeters; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Torque left, Torque right) { - return left._newtonMeters >= right._newtonMeters; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Torque left, Torque right) { - return left._newtonMeters < right._newtonMeters; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Torque left, Torque right) { - return left._newtonMeters > right._newtonMeters; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Torque left, Torque right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtonMeters == right._newtonMeters; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Torque left, Torque right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._newtonMeters != right._newtonMeters; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1264,7 +1051,7 @@ public override bool Equals(object obj) return false; } - return _newtonMeters.Equals(((Torque) obj)._newtonMeters); + return AsBaseUnitNewtonMeters().Equals(((Torque) obj).AsBaseUnitNewtonMeters()); } /// @@ -1277,12 +1064,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Torque other, Torque maxError) { - return Math.Abs(_newtonMeters - other._newtonMeters) <= maxError._newtonMeters; + return Math.Abs(AsBaseUnitNewtonMeters() - other.AsBaseUnitNewtonMeters()) <= maxError.AsBaseUnitNewtonMeters(); } public override int GetHashCode() { - return _newtonMeters.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1292,54 +1079,39 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(TorqueUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitNewtonMeters(); + switch (unit) { - case TorqueUnit.KilogramForceCentimeter: - return KilogramForceCentimeters; - case TorqueUnit.KilogramForceMeter: - return KilogramForceMeters; - case TorqueUnit.KilogramForceMillimeter: - return KilogramForceMillimeters; - case TorqueUnit.KilonewtonCentimeter: - return KilonewtonCentimeters; - case TorqueUnit.KilonewtonMeter: - return KilonewtonMeters; - case TorqueUnit.KilonewtonMillimeter: - return KilonewtonMillimeters; - case TorqueUnit.KilopoundForceFoot: - return KilopoundForceFeet; - case TorqueUnit.KilopoundForceInch: - return KilopoundForceInches; - case TorqueUnit.MeganewtonCentimeter: - return MeganewtonCentimeters; - case TorqueUnit.MeganewtonMeter: - return MeganewtonMeters; - case TorqueUnit.MeganewtonMillimeter: - return MeganewtonMillimeters; - case TorqueUnit.MegapoundForceFoot: - return MegapoundForceFeet; - case TorqueUnit.MegapoundForceInch: - return MegapoundForceInches; - case TorqueUnit.NewtonCentimeter: - return NewtonCentimeters; - case TorqueUnit.NewtonMeter: - return NewtonMeters; - case TorqueUnit.NewtonMillimeter: - return NewtonMillimeters; - case TorqueUnit.PoundForceFoot: - return PoundForceFeet; - case TorqueUnit.PoundForceInch: - return PoundForceInches; - case TorqueUnit.TonneForceCentimeter: - return TonneForceCentimeters; - case TorqueUnit.TonneForceMeter: - return TonneForceMeters; - case TorqueUnit.TonneForceMillimeter: - return TonneForceMillimeters; + case TorqueUnit.KilogramForceCentimeter: return baseUnitValue*10.1971619222242; + case TorqueUnit.KilogramForceMeter: return baseUnitValue*0.101971619222242; + case TorqueUnit.KilogramForceMillimeter: return baseUnitValue*101.971619222242; + case TorqueUnit.KilonewtonCentimeter: return (baseUnitValue*100) / 1e3d; + case TorqueUnit.KilonewtonMeter: return (baseUnitValue) / 1e3d; + case TorqueUnit.KilonewtonMillimeter: return (baseUnitValue*1000) / 1e3d; + case TorqueUnit.KilopoundForceFoot: return (baseUnitValue*0.737562085483396) / 1e3d; + case TorqueUnit.KilopoundForceInch: return (baseUnitValue*8.85074502580075) / 1e3d; + case TorqueUnit.MeganewtonCentimeter: return (baseUnitValue*100) / 1e6d; + case TorqueUnit.MeganewtonMeter: return (baseUnitValue) / 1e6d; + case TorqueUnit.MeganewtonMillimeter: return (baseUnitValue*1000) / 1e6d; + case TorqueUnit.MegapoundForceFoot: return (baseUnitValue*0.737562085483396) / 1e6d; + case TorqueUnit.MegapoundForceInch: return (baseUnitValue*8.85074502580075) / 1e6d; + case TorqueUnit.NewtonCentimeter: return baseUnitValue*100; + case TorqueUnit.NewtonMeter: return baseUnitValue; + case TorqueUnit.NewtonMillimeter: return baseUnitValue*1000; + case TorqueUnit.PoundForceFoot: return baseUnitValue*0.737562085483396; + case TorqueUnit.PoundForceInch: return baseUnitValue*8.85074502580075; + case TorqueUnit.TonneForceCentimeter: return baseUnitValue*0.0101971619222242; + case TorqueUnit.TonneForceMeter: return baseUnitValue*0.000101971619222242; + case TorqueUnit.TonneForceMillimeter: return baseUnitValue*0.101971619222242; default: throw new NotImplementedException("unit: " + unit); @@ -1381,7 +1153,11 @@ public static Torque Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1400,17 +1176,24 @@ public static Torque Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Torque Parse(string str, [CanBeNull] Culture culture) + public static Torque Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1436,16 +1219,41 @@ public static bool TryParse([CanBeNull] string str, out Torque result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Torque result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Torque result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1458,6 +1266,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1471,11 +1280,14 @@ public static TorqueUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static TorqueUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1484,6 +1296,8 @@ public static TorqueUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1496,18 +1310,18 @@ public static TorqueUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static TorqueUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static TorqueUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == TorqueUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized TorqueUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1516,6 +1330,7 @@ static TorqueUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is NewtonMeter /// @@ -1527,7 +1342,7 @@ static TorqueUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1544,74 +1359,149 @@ public string ToString(TorqueUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(TorqueUnit unit, [CanBeNull] Culture culture) + public string ToString( + TorqueUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(TorqueUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + TorqueUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(TorqueUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + TorqueUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Torque /// - public static Torque MaxValue - { - get - { - return new Torque(double.MaxValue); - } - } + public static Torque MaxValue => new Torque(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Torque /// - public static Torque MinValue + public static Torque MinValue => new Torque(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitNewtonMeters() { - get + if (Unit == TorqueUnit.NewtonMeter) { return _value; } + + switch (Unit) { - return new Torque(double.MinValue); - } - } - } + case TorqueUnit.KilogramForceCentimeter: return _value*0.0980665019960652; + case TorqueUnit.KilogramForceMeter: return _value*9.80665019960652; + case TorqueUnit.KilogramForceMillimeter: return _value*0.00980665019960652; + case TorqueUnit.KilonewtonCentimeter: return (_value*0.01) * 1e3d; + case TorqueUnit.KilonewtonMeter: return (_value) * 1e3d; + case TorqueUnit.KilonewtonMillimeter: return (_value*0.001) * 1e3d; + case TorqueUnit.KilopoundForceFoot: return (_value*1.3558180656) * 1e3d; + case TorqueUnit.KilopoundForceInch: return (_value*0.1129848388) * 1e3d; + case TorqueUnit.MeganewtonCentimeter: return (_value*0.01) * 1e6d; + case TorqueUnit.MeganewtonMeter: return (_value) * 1e6d; + case TorqueUnit.MeganewtonMillimeter: return (_value*0.001) * 1e6d; + case TorqueUnit.MegapoundForceFoot: return (_value*1.3558180656) * 1e6d; + case TorqueUnit.MegapoundForceInch: return (_value*0.1129848388) * 1e6d; + case TorqueUnit.NewtonCentimeter: return _value*0.01; + case TorqueUnit.NewtonMeter: return _value; + case TorqueUnit.NewtonMillimeter: return _value*0.001; + case TorqueUnit.PoundForceFoot: return _value*1.3558180656; + case TorqueUnit.PoundForceInch: return _value*0.1129848388; + case TorqueUnit.TonneForceCentimeter: return _value*98.0665019960652; + case TorqueUnit.TonneForceMeter: return _value*9806.65019960653; + case TorqueUnit.TonneForceMillimeter: return _value*9.80665019960652; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(TorqueUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs index 4d4a663fcd..10dfdf9707 100644 --- a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct VitaminA : IComparable, IComparable #endif { /// - /// Base unit of VitaminA. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VitaminAUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. /// - private readonly double _internationalUnits; + public VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public VitaminA() : this(0) + public VitaminA() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public VitaminA(double internationalunits) { - _internationalUnits = Convert.ToDouble(internationalunits); + _value = Convert.ToDouble(internationalunits); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + VitaminA(double numericValue, VitaminAUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit InternationalUnit. + /// + /// Value assuming base unit InternationalUnit. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - VitaminA(long internationalunits) - { - _internationalUnits = Convert.ToDouble(internationalunits); - } + VitaminA(long internationalunits) : this(Convert.ToDouble(internationalunits), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit InternationalUnit. + /// + /// Value assuming base unit InternationalUnit. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - VitaminA(decimal internationalunits) - { - _internationalUnits = Convert.ToDouble(internationalunits); - } + VitaminA(decimal internationalunits) : this(Convert.ToDouble(internationalunits), BaseUnit) { } #region Properties @@ -119,32 +156,22 @@ public VitaminA(double internationalunits) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static VitaminAUnit BaseUnit - { - get { return VitaminAUnit.InternationalUnit; } - } + public static VitaminAUnit BaseUnit => VitaminAUnit.InternationalUnit; /// /// All units of measurement for the VitaminA quantity. /// public static VitaminAUnit[] Units { get; } = Enum.GetValues(typeof(VitaminAUnit)).Cast().ToArray(); - /// /// Get VitaminA in InternationalUnits. /// - public double InternationalUnits - { - get { return _internationalUnits; } - } + public double InternationalUnits => As(VitaminAUnit.InternationalUnit); #endregion #region Static - public static VitaminA Zero - { - get { return new VitaminA(); } - } + public static VitaminA Zero => new VitaminA(0, BaseUnit); /// /// Get VitaminA from InternationalUnits. @@ -152,17 +179,13 @@ public static VitaminA Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VitaminA FromInternationalUnits(double internationalunits) - { - double value = (double) internationalunits; - return new VitaminA(value); - } #else public static VitaminA FromInternationalUnits(QuantityValue internationalunits) +#endif { double value = (double) internationalunits; - return new VitaminA((value)); + return new VitaminA(value, VitaminAUnit.InternationalUnit); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -197,14 +220,7 @@ public static VitaminA From(double value, VitaminAUnit fromUnit) public static VitaminA From(QuantityValue value, VitaminAUnit fromUnit) #endif { - switch (fromUnit) - { - case VitaminAUnit.InternationalUnit: - return FromInternationalUnits(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new VitaminA((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -221,14 +237,8 @@ public static VitaminA From(QuantityValue value, VitaminAUnit fromUnit) { return null; } - switch (fromUnit) - { - case VitaminAUnit.InternationalUnit: - return FromInternationalUnits(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new VitaminA((double)value.Value, fromUnit); } #endif @@ -247,12 +257,29 @@ public static string GetAbbreviation(VitaminAUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(VitaminAUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + VitaminAUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -263,37 +290,37 @@ public static string GetAbbreviation(VitaminAUnit unit, [CanBeNull] Culture cult #if !WINDOWS_UWP public static VitaminA operator -(VitaminA right) { - return new VitaminA(-right._internationalUnits); + return new VitaminA(-right.Value, right.Unit); } public static VitaminA operator +(VitaminA left, VitaminA right) { - return new VitaminA(left._internationalUnits + right._internationalUnits); + return new VitaminA(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static VitaminA operator -(VitaminA left, VitaminA right) { - return new VitaminA(left._internationalUnits - right._internationalUnits); + return new VitaminA(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static VitaminA operator *(double left, VitaminA right) { - return new VitaminA(left*right._internationalUnits); + return new VitaminA(left * right.Value, right.Unit); } public static VitaminA operator *(VitaminA left, double right) { - return new VitaminA(left._internationalUnits*(double)right); + return new VitaminA(left.Value * right, left.Unit); } public static VitaminA operator /(VitaminA left, double right) { - return new VitaminA(left._internationalUnits/(double)right); + return new VitaminA(left.Value / right, left.Unit); } public static double operator /(VitaminA left, VitaminA right) { - return Convert.ToDouble(left._internationalUnits/right._internationalUnits); + return left.InternationalUnits / right.InternationalUnits; } #endif @@ -316,43 +343,43 @@ public int CompareTo(object obj) #endif int CompareTo(VitaminA other) { - return _internationalUnits.CompareTo(other._internationalUnits); + return AsBaseUnitInternationalUnits().CompareTo(other.AsBaseUnitInternationalUnits()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(VitaminA left, VitaminA right) { - return left._internationalUnits <= right._internationalUnits; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(VitaminA left, VitaminA right) { - return left._internationalUnits >= right._internationalUnits; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(VitaminA left, VitaminA right) { - return left._internationalUnits < right._internationalUnits; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(VitaminA left, VitaminA right) { - return left._internationalUnits > right._internationalUnits; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(VitaminA left, VitaminA right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._internationalUnits == right._internationalUnits; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(VitaminA left, VitaminA right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._internationalUnits != right._internationalUnits; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -364,7 +391,7 @@ public override bool Equals(object obj) return false; } - return _internationalUnits.Equals(((VitaminA) obj)._internationalUnits); + return AsBaseUnitInternationalUnits().Equals(((VitaminA) obj).AsBaseUnitInternationalUnits()); } /// @@ -377,12 +404,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(VitaminA other, VitaminA maxError) { - return Math.Abs(_internationalUnits - other._internationalUnits) <= maxError._internationalUnits; + return Math.Abs(AsBaseUnitInternationalUnits() - other.AsBaseUnitInternationalUnits()) <= maxError.AsBaseUnitInternationalUnits(); } public override int GetHashCode() { - return _internationalUnits.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -392,14 +419,19 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(VitaminAUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitInternationalUnits(); + switch (unit) { - case VitaminAUnit.InternationalUnit: - return InternationalUnits; + case VitaminAUnit.InternationalUnit: return baseUnitValue; default: throw new NotImplementedException("unit: " + unit); @@ -441,7 +473,11 @@ public static VitaminA Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -460,17 +496,24 @@ public static VitaminA Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static VitaminA Parse(string str, [CanBeNull] Culture culture) + public static VitaminA Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -496,16 +539,41 @@ public static bool TryParse([CanBeNull] string str, out VitaminA result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out VitaminA result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out VitaminA result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -518,6 +586,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -531,11 +600,14 @@ public static VitaminAUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static VitaminAUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -544,6 +616,8 @@ public static VitaminAUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -556,18 +630,18 @@ public static VitaminAUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static VitaminAUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static VitaminAUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == VitaminAUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VitaminAUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -576,6 +650,7 @@ static VitaminAUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is InternationalUnit /// @@ -587,7 +662,7 @@ static VitaminAUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -604,74 +679,129 @@ public string ToString(VitaminAUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(VitaminAUnit unit, [CanBeNull] Culture culture) + public string ToString( + VitaminAUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(VitaminAUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + VitaminAUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(VitaminAUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + VitaminAUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of VitaminA /// - public static VitaminA MaxValue - { - get - { - return new VitaminA(double.MaxValue); - } - } + public static VitaminA MaxValue => new VitaminA(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of VitaminA /// - public static VitaminA MinValue + public static VitaminA MinValue => new VitaminA(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitInternationalUnits() { - get + if (Unit == VitaminAUnit.InternationalUnit) { return _value; } + + switch (Unit) { - return new VitaminA(double.MinValue); - } - } - } + case VitaminAUnit.InternationalUnit: return _value; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(VitaminAUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs index be49dee1e3..61b11c503b 100644 --- a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct Volume : IComparable, IComparable #endif { /// - /// Base unit of Volume. + /// The numeric value this quantity was constructed with. /// - private readonly double _cubicMeters; + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VolumeUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. + /// +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public Volume() : this(0) + public Volume() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public Volume(double cubicmeters) { - _cubicMeters = Convert.ToDouble(cubicmeters); + _value = Convert.ToDouble(cubicmeters); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + Volume(double numericValue, VolumeUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit CubicMeter. + /// + /// Value assuming base unit CubicMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Volume(long cubicmeters) - { - _cubicMeters = Convert.ToDouble(cubicmeters); - } + Volume(long cubicmeters) : this(Convert.ToDouble(cubicmeters), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit CubicMeter. + /// + /// Value assuming base unit CubicMeter. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - Volume(decimal cubicmeters) - { - _cubicMeters = Convert.ToDouble(cubicmeters); - } + Volume(decimal cubicmeters) : this(Convert.ToDouble(cubicmeters), BaseUnit) { } #region Properties @@ -119,362 +156,188 @@ public Volume(double cubicmeters) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static VolumeUnit BaseUnit - { - get { return VolumeUnit.CubicMeter; } - } + public static VolumeUnit BaseUnit => VolumeUnit.CubicMeter; /// /// All units of measurement for the Volume quantity. /// public static VolumeUnit[] Units { get; } = Enum.GetValues(typeof(VolumeUnit)).Cast().ToArray(); - /// /// Get Volume in AuTablespoons. /// - public double AuTablespoons - { - get { return _cubicMeters/2e-5; } - } - + public double AuTablespoons => As(VolumeUnit.AuTablespoon); /// /// Get Volume in Centiliters. /// - public double Centiliters - { - get { return (_cubicMeters*1e3) / 1e-2d; } - } - + public double Centiliters => As(VolumeUnit.Centiliter); /// /// Get Volume in CubicCentimeters. /// - public double CubicCentimeters - { - get { return _cubicMeters*1e6; } - } - + public double CubicCentimeters => As(VolumeUnit.CubicCentimeter); /// /// Get Volume in CubicDecimeters. /// - public double CubicDecimeters - { - get { return _cubicMeters*1e3; } - } - + public double CubicDecimeters => As(VolumeUnit.CubicDecimeter); /// /// Get Volume in CubicFeet. /// - public double CubicFeet - { - get { return _cubicMeters/0.0283168; } - } - + public double CubicFeet => As(VolumeUnit.CubicFoot); /// /// Get Volume in CubicInches. /// - public double CubicInches - { - get { return _cubicMeters/(1.6387*1e-5); } - } - + public double CubicInches => As(VolumeUnit.CubicInch); /// /// Get Volume in CubicKilometers. /// - public double CubicKilometers - { - get { return _cubicMeters/1e9; } - } - + public double CubicKilometers => As(VolumeUnit.CubicKilometer); /// /// Get Volume in CubicMeters. /// - public double CubicMeters - { - get { return _cubicMeters; } - } - + public double CubicMeters => As(VolumeUnit.CubicMeter); /// /// Get Volume in CubicMicrometers. /// - public double CubicMicrometers - { - get { return _cubicMeters*1e18; } - } - + public double CubicMicrometers => As(VolumeUnit.CubicMicrometer); /// /// Get Volume in CubicMiles. /// - public double CubicMiles - { - get { return _cubicMeters/(4.16818183*1e9); } - } - + public double CubicMiles => As(VolumeUnit.CubicMile); /// /// Get Volume in CubicMillimeters. /// - public double CubicMillimeters - { - get { return _cubicMeters*1e9; } - } - + public double CubicMillimeters => As(VolumeUnit.CubicMillimeter); /// /// Get Volume in CubicYards. /// - public double CubicYards - { - get { return _cubicMeters/0.764554858; } - } - + public double CubicYards => As(VolumeUnit.CubicYard); /// /// Get Volume in Deciliters. /// - public double Deciliters - { - get { return (_cubicMeters*1e3) / 1e-1d; } - } - + public double Deciliters => As(VolumeUnit.Deciliter); /// /// Get Volume in HectocubicFeet. /// - public double HectocubicFeet - { - get { return (_cubicMeters/0.0283168) / 1e2d; } - } - + public double HectocubicFeet => As(VolumeUnit.HectocubicFoot); /// /// Get Volume in HectocubicMeters. /// - public double HectocubicMeters - { - get { return (_cubicMeters) / 1e2d; } - } - + public double HectocubicMeters => As(VolumeUnit.HectocubicMeter); /// /// Get Volume in Hectoliters. /// - public double Hectoliters - { - get { return (_cubicMeters*1e3) / 1e2d; } - } - + public double Hectoliters => As(VolumeUnit.Hectoliter); /// /// Get Volume in ImperialBeerBarrels. /// - public double ImperialBeerBarrels - { - get { return _cubicMeters/0.16365924; } - } - + public double ImperialBeerBarrels => As(VolumeUnit.ImperialBeerBarrel); /// /// Get Volume in ImperialGallons. /// - public double ImperialGallons - { - get { return _cubicMeters/0.00454609000000181429905810072407; } - } - + public double ImperialGallons => As(VolumeUnit.ImperialGallon); /// /// Get Volume in ImperialOunces. /// - public double ImperialOunces - { - get { return _cubicMeters/2.8413062499962901241875439064617e-5; } - } - + public double ImperialOunces => As(VolumeUnit.ImperialOunce); /// /// Get Volume in KilocubicFeet. /// - public double KilocubicFeet - { - get { return (_cubicMeters/0.0283168) / 1e3d; } - } - + public double KilocubicFeet => As(VolumeUnit.KilocubicFoot); /// /// Get Volume in KilocubicMeters. /// - public double KilocubicMeters - { - get { return (_cubicMeters) / 1e3d; } - } - + public double KilocubicMeters => As(VolumeUnit.KilocubicMeter); /// /// Get Volume in KiloimperialGallons. /// - public double KiloimperialGallons - { - get { return (_cubicMeters/0.00454609000000181429905810072407) / 1e3d; } - } - + public double KiloimperialGallons => As(VolumeUnit.KiloimperialGallon); /// /// Get Volume in KilousGallons. /// - public double KilousGallons - { - get { return (_cubicMeters/0.00378541) / 1e3d; } - } - + public double KilousGallons => As(VolumeUnit.KilousGallon); /// /// Get Volume in Liters. /// - public double Liters - { - get { return _cubicMeters*1e3; } - } - + public double Liters => As(VolumeUnit.Liter); /// /// Get Volume in MegacubicFeet. /// - public double MegacubicFeet - { - get { return (_cubicMeters/0.0283168) / 1e6d; } - } - + public double MegacubicFeet => As(VolumeUnit.MegacubicFoot); /// /// Get Volume in MegaimperialGallons. /// - public double MegaimperialGallons - { - get { return (_cubicMeters/0.00454609000000181429905810072407) / 1e6d; } - } - + public double MegaimperialGallons => As(VolumeUnit.MegaimperialGallon); /// /// Get Volume in MegausGallons. /// - public double MegausGallons - { - get { return (_cubicMeters/0.00378541) / 1e6d; } - } - + public double MegausGallons => As(VolumeUnit.MegausGallon); /// /// Get Volume in MetricCups. /// - public double MetricCups - { - get { return _cubicMeters/0.00025; } - } - + public double MetricCups => As(VolumeUnit.MetricCup); /// /// Get Volume in MetricTeaspoons. /// - public double MetricTeaspoons - { - get { return _cubicMeters/0.5e-5; } - } - + public double MetricTeaspoons => As(VolumeUnit.MetricTeaspoon); /// /// Get Volume in Microliters. /// - public double Microliters - { - get { return (_cubicMeters*1e3) / 1e-6d; } - } - + public double Microliters => As(VolumeUnit.Microliter); /// /// Get Volume in Milliliters. /// - public double Milliliters - { - get { return (_cubicMeters*1e3) / 1e-3d; } - } - + public double Milliliters => As(VolumeUnit.Milliliter); /// /// Get Volume in OilBarrels. /// - public double OilBarrels - { - get { return _cubicMeters/0.158987294928; } - } - + public double OilBarrels => As(VolumeUnit.OilBarrel); /// /// Get Volume in Tablespoons. /// [System.Obsolete("Deprecated due to github issue #134, please use UsTablespoon instead")] - public double Tablespoons - { - get { return _cubicMeters/1.478676478125e-5; } - } - + public double Tablespoons => As(VolumeUnit.Tablespoon); /// /// Get Volume in Teaspoons. /// [System.Obsolete("Deprecated due to github issue #134, please use UsTeaspoon instead")] - public double Teaspoons - { - get { return _cubicMeters/4.92892159375e-6; } - } - + public double Teaspoons => As(VolumeUnit.Teaspoon); /// /// Get Volume in UkTablespoons. /// - public double UkTablespoons - { - get { return _cubicMeters/1.5e-5; } - } - + public double UkTablespoons => As(VolumeUnit.UkTablespoon); /// /// Get Volume in UsBeerBarrels. /// - public double UsBeerBarrels - { - get { return _cubicMeters/0.1173477658; } - } - + public double UsBeerBarrels => As(VolumeUnit.UsBeerBarrel); /// /// Get Volume in UsCustomaryCups. /// - public double UsCustomaryCups - { - get { return _cubicMeters/0.0002365882365; } - } - + public double UsCustomaryCups => As(VolumeUnit.UsCustomaryCup); /// /// Get Volume in UsGallons. /// - public double UsGallons - { - get { return _cubicMeters/0.00378541; } - } - + public double UsGallons => As(VolumeUnit.UsGallon); /// /// Get Volume in UsLegalCups. /// - public double UsLegalCups - { - get { return _cubicMeters/0.00024; } - } - + public double UsLegalCups => As(VolumeUnit.UsLegalCup); /// /// Get Volume in UsOunces. /// - public double UsOunces - { - get { return _cubicMeters/2.957352956253760505068307980135e-5; } - } - + public double UsOunces => As(VolumeUnit.UsOunce); /// /// Get Volume in UsTablespoons. /// - public double UsTablespoons - { - get { return _cubicMeters/1.478676478125e-5; } - } - + public double UsTablespoons => As(VolumeUnit.UsTablespoon); /// /// Get Volume in UsTeaspoons. /// - public double UsTeaspoons - { - get { return _cubicMeters/4.92892159375e-6; } - } + public double UsTeaspoons => As(VolumeUnit.UsTeaspoon); #endregion #region Static - public static Volume Zero - { - get { return new Volume(); } - } + public static Volume Zero => new Volume(0, BaseUnit); /// /// Get Volume from AuTablespoons. @@ -482,17 +345,13 @@ public static Volume Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromAuTablespoons(double autablespoons) - { - double value = (double) autablespoons; - return new Volume(value*2e-5); - } #else public static Volume FromAuTablespoons(QuantityValue autablespoons) +#endif { double value = (double) autablespoons; - return new Volume((value*2e-5)); + return new Volume(value, VolumeUnit.AuTablespoon); } -#endif /// /// Get Volume from Centiliters. @@ -500,17 +359,13 @@ public static Volume FromAuTablespoons(QuantityValue autablespoons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCentiliters(double centiliters) - { - double value = (double) centiliters; - return new Volume((value/1e3) * 1e-2d); - } #else public static Volume FromCentiliters(QuantityValue centiliters) +#endif { double value = (double) centiliters; - return new Volume(((value/1e3) * 1e-2d)); + return new Volume(value, VolumeUnit.Centiliter); } -#endif /// /// Get Volume from CubicCentimeters. @@ -518,17 +373,13 @@ public static Volume FromCentiliters(QuantityValue centiliters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCubicCentimeters(double cubiccentimeters) - { - double value = (double) cubiccentimeters; - return new Volume(value/1e6); - } #else public static Volume FromCubicCentimeters(QuantityValue cubiccentimeters) +#endif { double value = (double) cubiccentimeters; - return new Volume((value/1e6)); + return new Volume(value, VolumeUnit.CubicCentimeter); } -#endif /// /// Get Volume from CubicDecimeters. @@ -536,17 +387,13 @@ public static Volume FromCubicCentimeters(QuantityValue cubiccentimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCubicDecimeters(double cubicdecimeters) - { - double value = (double) cubicdecimeters; - return new Volume(value/1e3); - } #else public static Volume FromCubicDecimeters(QuantityValue cubicdecimeters) +#endif { double value = (double) cubicdecimeters; - return new Volume((value/1e3)); + return new Volume(value, VolumeUnit.CubicDecimeter); } -#endif /// /// Get Volume from CubicFeet. @@ -554,17 +401,13 @@ public static Volume FromCubicDecimeters(QuantityValue cubicdecimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCubicFeet(double cubicfeet) - { - double value = (double) cubicfeet; - return new Volume(value*0.0283168); - } #else public static Volume FromCubicFeet(QuantityValue cubicfeet) +#endif { double value = (double) cubicfeet; - return new Volume((value*0.0283168)); + return new Volume(value, VolumeUnit.CubicFoot); } -#endif /// /// Get Volume from CubicInches. @@ -572,17 +415,13 @@ public static Volume FromCubicFeet(QuantityValue cubicfeet) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCubicInches(double cubicinches) - { - double value = (double) cubicinches; - return new Volume(value*1.6387*1e-5); - } #else public static Volume FromCubicInches(QuantityValue cubicinches) +#endif { double value = (double) cubicinches; - return new Volume((value*1.6387*1e-5)); + return new Volume(value, VolumeUnit.CubicInch); } -#endif /// /// Get Volume from CubicKilometers. @@ -590,17 +429,13 @@ public static Volume FromCubicInches(QuantityValue cubicinches) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCubicKilometers(double cubickilometers) - { - double value = (double) cubickilometers; - return new Volume(value*1e9); - } #else public static Volume FromCubicKilometers(QuantityValue cubickilometers) +#endif { double value = (double) cubickilometers; - return new Volume((value*1e9)); + return new Volume(value, VolumeUnit.CubicKilometer); } -#endif /// /// Get Volume from CubicMeters. @@ -608,17 +443,13 @@ public static Volume FromCubicKilometers(QuantityValue cubickilometers) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCubicMeters(double cubicmeters) - { - double value = (double) cubicmeters; - return new Volume(value); - } #else public static Volume FromCubicMeters(QuantityValue cubicmeters) +#endif { double value = (double) cubicmeters; - return new Volume((value)); + return new Volume(value, VolumeUnit.CubicMeter); } -#endif /// /// Get Volume from CubicMicrometers. @@ -626,17 +457,13 @@ public static Volume FromCubicMeters(QuantityValue cubicmeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCubicMicrometers(double cubicmicrometers) - { - double value = (double) cubicmicrometers; - return new Volume(value/1e18); - } #else public static Volume FromCubicMicrometers(QuantityValue cubicmicrometers) +#endif { double value = (double) cubicmicrometers; - return new Volume((value/1e18)); + return new Volume(value, VolumeUnit.CubicMicrometer); } -#endif /// /// Get Volume from CubicMiles. @@ -644,17 +471,13 @@ public static Volume FromCubicMicrometers(QuantityValue cubicmicrometers) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCubicMiles(double cubicmiles) - { - double value = (double) cubicmiles; - return new Volume(value*4.16818183*1e9); - } #else public static Volume FromCubicMiles(QuantityValue cubicmiles) +#endif { double value = (double) cubicmiles; - return new Volume((value*4.16818183*1e9)); + return new Volume(value, VolumeUnit.CubicMile); } -#endif /// /// Get Volume from CubicMillimeters. @@ -662,17 +485,13 @@ public static Volume FromCubicMiles(QuantityValue cubicmiles) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCubicMillimeters(double cubicmillimeters) - { - double value = (double) cubicmillimeters; - return new Volume(value/1e9); - } #else public static Volume FromCubicMillimeters(QuantityValue cubicmillimeters) +#endif { double value = (double) cubicmillimeters; - return new Volume((value/1e9)); + return new Volume(value, VolumeUnit.CubicMillimeter); } -#endif /// /// Get Volume from CubicYards. @@ -680,17 +499,13 @@ public static Volume FromCubicMillimeters(QuantityValue cubicmillimeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromCubicYards(double cubicyards) - { - double value = (double) cubicyards; - return new Volume(value*0.764554858); - } #else public static Volume FromCubicYards(QuantityValue cubicyards) +#endif { double value = (double) cubicyards; - return new Volume((value*0.764554858)); + return new Volume(value, VolumeUnit.CubicYard); } -#endif /// /// Get Volume from Deciliters. @@ -698,17 +513,13 @@ public static Volume FromCubicYards(QuantityValue cubicyards) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromDeciliters(double deciliters) - { - double value = (double) deciliters; - return new Volume((value/1e3) * 1e-1d); - } #else public static Volume FromDeciliters(QuantityValue deciliters) +#endif { double value = (double) deciliters; - return new Volume(((value/1e3) * 1e-1d)); + return new Volume(value, VolumeUnit.Deciliter); } -#endif /// /// Get Volume from HectocubicFeet. @@ -716,17 +527,13 @@ public static Volume FromDeciliters(QuantityValue deciliters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromHectocubicFeet(double hectocubicfeet) - { - double value = (double) hectocubicfeet; - return new Volume((value*0.0283168) * 1e2d); - } #else public static Volume FromHectocubicFeet(QuantityValue hectocubicfeet) +#endif { double value = (double) hectocubicfeet; - return new Volume(((value*0.0283168) * 1e2d)); + return new Volume(value, VolumeUnit.HectocubicFoot); } -#endif /// /// Get Volume from HectocubicMeters. @@ -734,17 +541,13 @@ public static Volume FromHectocubicFeet(QuantityValue hectocubicfeet) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromHectocubicMeters(double hectocubicmeters) - { - double value = (double) hectocubicmeters; - return new Volume((value) * 1e2d); - } #else public static Volume FromHectocubicMeters(QuantityValue hectocubicmeters) +#endif { double value = (double) hectocubicmeters; - return new Volume(((value) * 1e2d)); + return new Volume(value, VolumeUnit.HectocubicMeter); } -#endif /// /// Get Volume from Hectoliters. @@ -752,17 +555,13 @@ public static Volume FromHectocubicMeters(QuantityValue hectocubicmeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromHectoliters(double hectoliters) - { - double value = (double) hectoliters; - return new Volume((value/1e3) * 1e2d); - } #else public static Volume FromHectoliters(QuantityValue hectoliters) +#endif { double value = (double) hectoliters; - return new Volume(((value/1e3) * 1e2d)); + return new Volume(value, VolumeUnit.Hectoliter); } -#endif /// /// Get Volume from ImperialBeerBarrels. @@ -770,17 +569,13 @@ public static Volume FromHectoliters(QuantityValue hectoliters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromImperialBeerBarrels(double imperialbeerbarrels) - { - double value = (double) imperialbeerbarrels; - return new Volume(value*0.16365924); - } #else public static Volume FromImperialBeerBarrels(QuantityValue imperialbeerbarrels) +#endif { double value = (double) imperialbeerbarrels; - return new Volume((value*0.16365924)); + return new Volume(value, VolumeUnit.ImperialBeerBarrel); } -#endif /// /// Get Volume from ImperialGallons. @@ -788,17 +583,13 @@ public static Volume FromImperialBeerBarrels(QuantityValue imperialbeerbarrels) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromImperialGallons(double imperialgallons) - { - double value = (double) imperialgallons; - return new Volume(value*0.00454609000000181429905810072407); - } #else public static Volume FromImperialGallons(QuantityValue imperialgallons) +#endif { double value = (double) imperialgallons; - return new Volume((value*0.00454609000000181429905810072407)); + return new Volume(value, VolumeUnit.ImperialGallon); } -#endif /// /// Get Volume from ImperialOunces. @@ -806,17 +597,13 @@ public static Volume FromImperialGallons(QuantityValue imperialgallons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromImperialOunces(double imperialounces) - { - double value = (double) imperialounces; - return new Volume(value*2.8413062499962901241875439064617e-5); - } #else public static Volume FromImperialOunces(QuantityValue imperialounces) +#endif { double value = (double) imperialounces; - return new Volume((value*2.8413062499962901241875439064617e-5)); + return new Volume(value, VolumeUnit.ImperialOunce); } -#endif /// /// Get Volume from KilocubicFeet. @@ -824,17 +611,13 @@ public static Volume FromImperialOunces(QuantityValue imperialounces) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromKilocubicFeet(double kilocubicfeet) - { - double value = (double) kilocubicfeet; - return new Volume((value*0.0283168) * 1e3d); - } #else public static Volume FromKilocubicFeet(QuantityValue kilocubicfeet) +#endif { double value = (double) kilocubicfeet; - return new Volume(((value*0.0283168) * 1e3d)); + return new Volume(value, VolumeUnit.KilocubicFoot); } -#endif /// /// Get Volume from KilocubicMeters. @@ -842,17 +625,13 @@ public static Volume FromKilocubicFeet(QuantityValue kilocubicfeet) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromKilocubicMeters(double kilocubicmeters) - { - double value = (double) kilocubicmeters; - return new Volume((value) * 1e3d); - } #else public static Volume FromKilocubicMeters(QuantityValue kilocubicmeters) +#endif { double value = (double) kilocubicmeters; - return new Volume(((value) * 1e3d)); + return new Volume(value, VolumeUnit.KilocubicMeter); } -#endif /// /// Get Volume from KiloimperialGallons. @@ -860,17 +639,13 @@ public static Volume FromKilocubicMeters(QuantityValue kilocubicmeters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromKiloimperialGallons(double kiloimperialgallons) - { - double value = (double) kiloimperialgallons; - return new Volume((value*0.00454609000000181429905810072407) * 1e3d); - } #else public static Volume FromKiloimperialGallons(QuantityValue kiloimperialgallons) +#endif { double value = (double) kiloimperialgallons; - return new Volume(((value*0.00454609000000181429905810072407) * 1e3d)); + return new Volume(value, VolumeUnit.KiloimperialGallon); } -#endif /// /// Get Volume from KilousGallons. @@ -878,17 +653,13 @@ public static Volume FromKiloimperialGallons(QuantityValue kiloimperialgallons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromKilousGallons(double kilousgallons) - { - double value = (double) kilousgallons; - return new Volume((value*0.00378541) * 1e3d); - } #else public static Volume FromKilousGallons(QuantityValue kilousgallons) +#endif { double value = (double) kilousgallons; - return new Volume(((value*0.00378541) * 1e3d)); + return new Volume(value, VolumeUnit.KilousGallon); } -#endif /// /// Get Volume from Liters. @@ -896,17 +667,13 @@ public static Volume FromKilousGallons(QuantityValue kilousgallons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromLiters(double liters) - { - double value = (double) liters; - return new Volume(value/1e3); - } #else public static Volume FromLiters(QuantityValue liters) +#endif { double value = (double) liters; - return new Volume((value/1e3)); + return new Volume(value, VolumeUnit.Liter); } -#endif /// /// Get Volume from MegacubicFeet. @@ -914,17 +681,13 @@ public static Volume FromLiters(QuantityValue liters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromMegacubicFeet(double megacubicfeet) - { - double value = (double) megacubicfeet; - return new Volume((value*0.0283168) * 1e6d); - } #else public static Volume FromMegacubicFeet(QuantityValue megacubicfeet) +#endif { double value = (double) megacubicfeet; - return new Volume(((value*0.0283168) * 1e6d)); + return new Volume(value, VolumeUnit.MegacubicFoot); } -#endif /// /// Get Volume from MegaimperialGallons. @@ -932,17 +695,13 @@ public static Volume FromMegacubicFeet(QuantityValue megacubicfeet) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromMegaimperialGallons(double megaimperialgallons) - { - double value = (double) megaimperialgallons; - return new Volume((value*0.00454609000000181429905810072407) * 1e6d); - } #else public static Volume FromMegaimperialGallons(QuantityValue megaimperialgallons) +#endif { double value = (double) megaimperialgallons; - return new Volume(((value*0.00454609000000181429905810072407) * 1e6d)); + return new Volume(value, VolumeUnit.MegaimperialGallon); } -#endif /// /// Get Volume from MegausGallons. @@ -950,17 +709,13 @@ public static Volume FromMegaimperialGallons(QuantityValue megaimperialgallons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromMegausGallons(double megausgallons) - { - double value = (double) megausgallons; - return new Volume((value*0.00378541) * 1e6d); - } #else public static Volume FromMegausGallons(QuantityValue megausgallons) +#endif { double value = (double) megausgallons; - return new Volume(((value*0.00378541) * 1e6d)); + return new Volume(value, VolumeUnit.MegausGallon); } -#endif /// /// Get Volume from MetricCups. @@ -968,17 +723,13 @@ public static Volume FromMegausGallons(QuantityValue megausgallons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromMetricCups(double metriccups) - { - double value = (double) metriccups; - return new Volume(value*0.00025); - } #else public static Volume FromMetricCups(QuantityValue metriccups) +#endif { double value = (double) metriccups; - return new Volume((value*0.00025)); + return new Volume(value, VolumeUnit.MetricCup); } -#endif /// /// Get Volume from MetricTeaspoons. @@ -986,17 +737,13 @@ public static Volume FromMetricCups(QuantityValue metriccups) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromMetricTeaspoons(double metricteaspoons) - { - double value = (double) metricteaspoons; - return new Volume(value*0.5e-5); - } #else public static Volume FromMetricTeaspoons(QuantityValue metricteaspoons) +#endif { double value = (double) metricteaspoons; - return new Volume((value*0.5e-5)); + return new Volume(value, VolumeUnit.MetricTeaspoon); } -#endif /// /// Get Volume from Microliters. @@ -1004,17 +751,13 @@ public static Volume FromMetricTeaspoons(QuantityValue metricteaspoons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromMicroliters(double microliters) - { - double value = (double) microliters; - return new Volume((value/1e3) * 1e-6d); - } #else public static Volume FromMicroliters(QuantityValue microliters) +#endif { double value = (double) microliters; - return new Volume(((value/1e3) * 1e-6d)); + return new Volume(value, VolumeUnit.Microliter); } -#endif /// /// Get Volume from Milliliters. @@ -1022,17 +765,13 @@ public static Volume FromMicroliters(QuantityValue microliters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromMilliliters(double milliliters) - { - double value = (double) milliliters; - return new Volume((value/1e3) * 1e-3d); - } #else public static Volume FromMilliliters(QuantityValue milliliters) +#endif { double value = (double) milliliters; - return new Volume(((value/1e3) * 1e-3d)); + return new Volume(value, VolumeUnit.Milliliter); } -#endif /// /// Get Volume from OilBarrels. @@ -1040,17 +779,13 @@ public static Volume FromMilliliters(QuantityValue milliliters) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromOilBarrels(double oilbarrels) - { - double value = (double) oilbarrels; - return new Volume(value*0.158987294928); - } #else public static Volume FromOilBarrels(QuantityValue oilbarrels) +#endif { double value = (double) oilbarrels; - return new Volume((value*0.158987294928)); + return new Volume(value, VolumeUnit.OilBarrel); } -#endif /// /// Get Volume from Tablespoons. @@ -1058,17 +793,13 @@ public static Volume FromOilBarrels(QuantityValue oilbarrels) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromTablespoons(double tablespoons) - { - double value = (double) tablespoons; - return new Volume(value*1.478676478125e-5); - } #else public static Volume FromTablespoons(QuantityValue tablespoons) +#endif { double value = (double) tablespoons; - return new Volume((value*1.478676478125e-5)); + return new Volume(value, VolumeUnit.Tablespoon); } -#endif /// /// Get Volume from Teaspoons. @@ -1076,17 +807,13 @@ public static Volume FromTablespoons(QuantityValue tablespoons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromTeaspoons(double teaspoons) - { - double value = (double) teaspoons; - return new Volume(value*4.92892159375e-6); - } #else public static Volume FromTeaspoons(QuantityValue teaspoons) +#endif { double value = (double) teaspoons; - return new Volume((value*4.92892159375e-6)); + return new Volume(value, VolumeUnit.Teaspoon); } -#endif /// /// Get Volume from UkTablespoons. @@ -1094,17 +821,13 @@ public static Volume FromTeaspoons(QuantityValue teaspoons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromUkTablespoons(double uktablespoons) - { - double value = (double) uktablespoons; - return new Volume(value*1.5e-5); - } #else public static Volume FromUkTablespoons(QuantityValue uktablespoons) +#endif { double value = (double) uktablespoons; - return new Volume((value*1.5e-5)); + return new Volume(value, VolumeUnit.UkTablespoon); } -#endif /// /// Get Volume from UsBeerBarrels. @@ -1112,17 +835,13 @@ public static Volume FromUkTablespoons(QuantityValue uktablespoons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromUsBeerBarrels(double usbeerbarrels) - { - double value = (double) usbeerbarrels; - return new Volume(value*0.1173477658); - } #else public static Volume FromUsBeerBarrels(QuantityValue usbeerbarrels) +#endif { double value = (double) usbeerbarrels; - return new Volume((value*0.1173477658)); + return new Volume(value, VolumeUnit.UsBeerBarrel); } -#endif /// /// Get Volume from UsCustomaryCups. @@ -1130,17 +849,13 @@ public static Volume FromUsBeerBarrels(QuantityValue usbeerbarrels) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromUsCustomaryCups(double uscustomarycups) - { - double value = (double) uscustomarycups; - return new Volume(value*0.0002365882365); - } #else public static Volume FromUsCustomaryCups(QuantityValue uscustomarycups) +#endif { double value = (double) uscustomarycups; - return new Volume((value*0.0002365882365)); + return new Volume(value, VolumeUnit.UsCustomaryCup); } -#endif /// /// Get Volume from UsGallons. @@ -1148,17 +863,13 @@ public static Volume FromUsCustomaryCups(QuantityValue uscustomarycups) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromUsGallons(double usgallons) - { - double value = (double) usgallons; - return new Volume(value*0.00378541); - } #else public static Volume FromUsGallons(QuantityValue usgallons) +#endif { double value = (double) usgallons; - return new Volume((value*0.00378541)); + return new Volume(value, VolumeUnit.UsGallon); } -#endif /// /// Get Volume from UsLegalCups. @@ -1166,17 +877,13 @@ public static Volume FromUsGallons(QuantityValue usgallons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromUsLegalCups(double uslegalcups) - { - double value = (double) uslegalcups; - return new Volume(value*0.00024); - } #else public static Volume FromUsLegalCups(QuantityValue uslegalcups) +#endif { double value = (double) uslegalcups; - return new Volume((value*0.00024)); + return new Volume(value, VolumeUnit.UsLegalCup); } -#endif /// /// Get Volume from UsOunces. @@ -1184,17 +891,13 @@ public static Volume FromUsLegalCups(QuantityValue uslegalcups) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromUsOunces(double usounces) - { - double value = (double) usounces; - return new Volume(value*2.957352956253760505068307980135e-5); - } #else public static Volume FromUsOunces(QuantityValue usounces) +#endif { double value = (double) usounces; - return new Volume((value*2.957352956253760505068307980135e-5)); + return new Volume(value, VolumeUnit.UsOunce); } -#endif /// /// Get Volume from UsTablespoons. @@ -1202,17 +905,13 @@ public static Volume FromUsOunces(QuantityValue usounces) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromUsTablespoons(double ustablespoons) - { - double value = (double) ustablespoons; - return new Volume(value*1.478676478125e-5); - } #else public static Volume FromUsTablespoons(QuantityValue ustablespoons) +#endif { double value = (double) ustablespoons; - return new Volume((value*1.478676478125e-5)); + return new Volume(value, VolumeUnit.UsTablespoon); } -#endif /// /// Get Volume from UsTeaspoons. @@ -1220,17 +919,13 @@ public static Volume FromUsTablespoons(QuantityValue ustablespoons) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static Volume FromUsTeaspoons(double usteaspoons) - { - double value = (double) usteaspoons; - return new Volume(value*4.92892159375e-6); - } #else public static Volume FromUsTeaspoons(QuantityValue usteaspoons) +#endif { double value = (double) usteaspoons; - return new Volume((value*4.92892159375e-6)); + return new Volume(value, VolumeUnit.UsTeaspoon); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1880,96 +1575,7 @@ public static Volume From(double value, VolumeUnit fromUnit) public static Volume From(QuantityValue value, VolumeUnit fromUnit) #endif { - switch (fromUnit) - { - case VolumeUnit.AuTablespoon: - return FromAuTablespoons(value); - case VolumeUnit.Centiliter: - return FromCentiliters(value); - case VolumeUnit.CubicCentimeter: - return FromCubicCentimeters(value); - case VolumeUnit.CubicDecimeter: - return FromCubicDecimeters(value); - case VolumeUnit.CubicFoot: - return FromCubicFeet(value); - case VolumeUnit.CubicInch: - return FromCubicInches(value); - case VolumeUnit.CubicKilometer: - return FromCubicKilometers(value); - case VolumeUnit.CubicMeter: - return FromCubicMeters(value); - case VolumeUnit.CubicMicrometer: - return FromCubicMicrometers(value); - case VolumeUnit.CubicMile: - return FromCubicMiles(value); - case VolumeUnit.CubicMillimeter: - return FromCubicMillimeters(value); - case VolumeUnit.CubicYard: - return FromCubicYards(value); - case VolumeUnit.Deciliter: - return FromDeciliters(value); - case VolumeUnit.HectocubicFoot: - return FromHectocubicFeet(value); - case VolumeUnit.HectocubicMeter: - return FromHectocubicMeters(value); - case VolumeUnit.Hectoliter: - return FromHectoliters(value); - case VolumeUnit.ImperialBeerBarrel: - return FromImperialBeerBarrels(value); - case VolumeUnit.ImperialGallon: - return FromImperialGallons(value); - case VolumeUnit.ImperialOunce: - return FromImperialOunces(value); - case VolumeUnit.KilocubicFoot: - return FromKilocubicFeet(value); - case VolumeUnit.KilocubicMeter: - return FromKilocubicMeters(value); - case VolumeUnit.KiloimperialGallon: - return FromKiloimperialGallons(value); - case VolumeUnit.KilousGallon: - return FromKilousGallons(value); - case VolumeUnit.Liter: - return FromLiters(value); - case VolumeUnit.MegacubicFoot: - return FromMegacubicFeet(value); - case VolumeUnit.MegaimperialGallon: - return FromMegaimperialGallons(value); - case VolumeUnit.MegausGallon: - return FromMegausGallons(value); - case VolumeUnit.MetricCup: - return FromMetricCups(value); - case VolumeUnit.MetricTeaspoon: - return FromMetricTeaspoons(value); - case VolumeUnit.Microliter: - return FromMicroliters(value); - case VolumeUnit.Milliliter: - return FromMilliliters(value); - case VolumeUnit.OilBarrel: - return FromOilBarrels(value); - case VolumeUnit.Tablespoon: - return FromTablespoons(value); - case VolumeUnit.Teaspoon: - return FromTeaspoons(value); - case VolumeUnit.UkTablespoon: - return FromUkTablespoons(value); - case VolumeUnit.UsBeerBarrel: - return FromUsBeerBarrels(value); - case VolumeUnit.UsCustomaryCup: - return FromUsCustomaryCups(value); - case VolumeUnit.UsGallon: - return FromUsGallons(value); - case VolumeUnit.UsLegalCup: - return FromUsLegalCups(value); - case VolumeUnit.UsOunce: - return FromUsOunces(value); - case VolumeUnit.UsTablespoon: - return FromUsTablespoons(value); - case VolumeUnit.UsTeaspoon: - return FromUsTeaspoons(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Volume((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1986,96 +1592,8 @@ public static Volume From(QuantityValue value, VolumeUnit fromUnit) { return null; } - switch (fromUnit) - { - case VolumeUnit.AuTablespoon: - return FromAuTablespoons(value.Value); - case VolumeUnit.Centiliter: - return FromCentiliters(value.Value); - case VolumeUnit.CubicCentimeter: - return FromCubicCentimeters(value.Value); - case VolumeUnit.CubicDecimeter: - return FromCubicDecimeters(value.Value); - case VolumeUnit.CubicFoot: - return FromCubicFeet(value.Value); - case VolumeUnit.CubicInch: - return FromCubicInches(value.Value); - case VolumeUnit.CubicKilometer: - return FromCubicKilometers(value.Value); - case VolumeUnit.CubicMeter: - return FromCubicMeters(value.Value); - case VolumeUnit.CubicMicrometer: - return FromCubicMicrometers(value.Value); - case VolumeUnit.CubicMile: - return FromCubicMiles(value.Value); - case VolumeUnit.CubicMillimeter: - return FromCubicMillimeters(value.Value); - case VolumeUnit.CubicYard: - return FromCubicYards(value.Value); - case VolumeUnit.Deciliter: - return FromDeciliters(value.Value); - case VolumeUnit.HectocubicFoot: - return FromHectocubicFeet(value.Value); - case VolumeUnit.HectocubicMeter: - return FromHectocubicMeters(value.Value); - case VolumeUnit.Hectoliter: - return FromHectoliters(value.Value); - case VolumeUnit.ImperialBeerBarrel: - return FromImperialBeerBarrels(value.Value); - case VolumeUnit.ImperialGallon: - return FromImperialGallons(value.Value); - case VolumeUnit.ImperialOunce: - return FromImperialOunces(value.Value); - case VolumeUnit.KilocubicFoot: - return FromKilocubicFeet(value.Value); - case VolumeUnit.KilocubicMeter: - return FromKilocubicMeters(value.Value); - case VolumeUnit.KiloimperialGallon: - return FromKiloimperialGallons(value.Value); - case VolumeUnit.KilousGallon: - return FromKilousGallons(value.Value); - case VolumeUnit.Liter: - return FromLiters(value.Value); - case VolumeUnit.MegacubicFoot: - return FromMegacubicFeet(value.Value); - case VolumeUnit.MegaimperialGallon: - return FromMegaimperialGallons(value.Value); - case VolumeUnit.MegausGallon: - return FromMegausGallons(value.Value); - case VolumeUnit.MetricCup: - return FromMetricCups(value.Value); - case VolumeUnit.MetricTeaspoon: - return FromMetricTeaspoons(value.Value); - case VolumeUnit.Microliter: - return FromMicroliters(value.Value); - case VolumeUnit.Milliliter: - return FromMilliliters(value.Value); - case VolumeUnit.OilBarrel: - return FromOilBarrels(value.Value); - case VolumeUnit.Tablespoon: - return FromTablespoons(value.Value); - case VolumeUnit.Teaspoon: - return FromTeaspoons(value.Value); - case VolumeUnit.UkTablespoon: - return FromUkTablespoons(value.Value); - case VolumeUnit.UsBeerBarrel: - return FromUsBeerBarrels(value.Value); - case VolumeUnit.UsCustomaryCup: - return FromUsCustomaryCups(value.Value); - case VolumeUnit.UsGallon: - return FromUsGallons(value.Value); - case VolumeUnit.UsLegalCup: - return FromUsLegalCups(value.Value); - case VolumeUnit.UsOunce: - return FromUsOunces(value.Value); - case VolumeUnit.UsTablespoon: - return FromUsTablespoons(value.Value); - case VolumeUnit.UsTeaspoon: - return FromUsTeaspoons(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new Volume((double)value.Value, fromUnit); } #endif @@ -2094,12 +1612,29 @@ public static string GetAbbreviation(VolumeUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + VolumeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -2110,37 +1645,37 @@ public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] Culture cultur #if !WINDOWS_UWP public static Volume operator -(Volume right) { - return new Volume(-right._cubicMeters); + return new Volume(-right.Value, right.Unit); } public static Volume operator +(Volume left, Volume right) { - return new Volume(left._cubicMeters + right._cubicMeters); + return new Volume(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static Volume operator -(Volume left, Volume right) { - return new Volume(left._cubicMeters - right._cubicMeters); + return new Volume(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static Volume operator *(double left, Volume right) { - return new Volume(left*right._cubicMeters); + return new Volume(left * right.Value, right.Unit); } public static Volume operator *(Volume left, double right) { - return new Volume(left._cubicMeters*(double)right); + return new Volume(left.Value * right, left.Unit); } public static Volume operator /(Volume left, double right) { - return new Volume(left._cubicMeters/(double)right); + return new Volume(left.Value / right, left.Unit); } public static double operator /(Volume left, Volume right) { - return Convert.ToDouble(left._cubicMeters/right._cubicMeters); + return left.CubicMeters / right.CubicMeters; } #endif @@ -2163,43 +1698,43 @@ public int CompareTo(object obj) #endif int CompareTo(Volume other) { - return _cubicMeters.CompareTo(other._cubicMeters); + return AsBaseUnitCubicMeters().CompareTo(other.AsBaseUnitCubicMeters()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(Volume left, Volume right) { - return left._cubicMeters <= right._cubicMeters; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(Volume left, Volume right) { - return left._cubicMeters >= right._cubicMeters; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(Volume left, Volume right) { - return left._cubicMeters < right._cubicMeters; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(Volume left, Volume right) { - return left._cubicMeters > right._cubicMeters; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(Volume left, Volume right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._cubicMeters == right._cubicMeters; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(Volume left, Volume right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._cubicMeters != right._cubicMeters; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -2211,7 +1746,7 @@ public override bool Equals(object obj) return false; } - return _cubicMeters.Equals(((Volume) obj)._cubicMeters); + return AsBaseUnitCubicMeters().Equals(((Volume) obj).AsBaseUnitCubicMeters()); } /// @@ -2224,12 +1759,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(Volume other, Volume maxError) { - return Math.Abs(_cubicMeters - other._cubicMeters) <= maxError._cubicMeters; + return Math.Abs(AsBaseUnitCubicMeters() - other.AsBaseUnitCubicMeters()) <= maxError.AsBaseUnitCubicMeters(); } public override int GetHashCode() { - return _cubicMeters.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -2239,96 +1774,60 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(VolumeUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitCubicMeters(); + switch (unit) { - case VolumeUnit.AuTablespoon: - return AuTablespoons; - case VolumeUnit.Centiliter: - return Centiliters; - case VolumeUnit.CubicCentimeter: - return CubicCentimeters; - case VolumeUnit.CubicDecimeter: - return CubicDecimeters; - case VolumeUnit.CubicFoot: - return CubicFeet; - case VolumeUnit.CubicInch: - return CubicInches; - case VolumeUnit.CubicKilometer: - return CubicKilometers; - case VolumeUnit.CubicMeter: - return CubicMeters; - case VolumeUnit.CubicMicrometer: - return CubicMicrometers; - case VolumeUnit.CubicMile: - return CubicMiles; - case VolumeUnit.CubicMillimeter: - return CubicMillimeters; - case VolumeUnit.CubicYard: - return CubicYards; - case VolumeUnit.Deciliter: - return Deciliters; - case VolumeUnit.HectocubicFoot: - return HectocubicFeet; - case VolumeUnit.HectocubicMeter: - return HectocubicMeters; - case VolumeUnit.Hectoliter: - return Hectoliters; - case VolumeUnit.ImperialBeerBarrel: - return ImperialBeerBarrels; - case VolumeUnit.ImperialGallon: - return ImperialGallons; - case VolumeUnit.ImperialOunce: - return ImperialOunces; - case VolumeUnit.KilocubicFoot: - return KilocubicFeet; - case VolumeUnit.KilocubicMeter: - return KilocubicMeters; - case VolumeUnit.KiloimperialGallon: - return KiloimperialGallons; - case VolumeUnit.KilousGallon: - return KilousGallons; - case VolumeUnit.Liter: - return Liters; - case VolumeUnit.MegacubicFoot: - return MegacubicFeet; - case VolumeUnit.MegaimperialGallon: - return MegaimperialGallons; - case VolumeUnit.MegausGallon: - return MegausGallons; - case VolumeUnit.MetricCup: - return MetricCups; - case VolumeUnit.MetricTeaspoon: - return MetricTeaspoons; - case VolumeUnit.Microliter: - return Microliters; - case VolumeUnit.Milliliter: - return Milliliters; - case VolumeUnit.OilBarrel: - return OilBarrels; - case VolumeUnit.Tablespoon: - return Tablespoons; - case VolumeUnit.Teaspoon: - return Teaspoons; - case VolumeUnit.UkTablespoon: - return UkTablespoons; - case VolumeUnit.UsBeerBarrel: - return UsBeerBarrels; - case VolumeUnit.UsCustomaryCup: - return UsCustomaryCups; - case VolumeUnit.UsGallon: - return UsGallons; - case VolumeUnit.UsLegalCup: - return UsLegalCups; - case VolumeUnit.UsOunce: - return UsOunces; - case VolumeUnit.UsTablespoon: - return UsTablespoons; - case VolumeUnit.UsTeaspoon: - return UsTeaspoons; + case VolumeUnit.AuTablespoon: return baseUnitValue/2e-5; + case VolumeUnit.Centiliter: return (baseUnitValue*1e3) / 1e-2d; + case VolumeUnit.CubicCentimeter: return baseUnitValue*1e6; + case VolumeUnit.CubicDecimeter: return baseUnitValue*1e3; + case VolumeUnit.CubicFoot: return baseUnitValue/0.0283168; + case VolumeUnit.CubicInch: return baseUnitValue/(1.6387*1e-5); + case VolumeUnit.CubicKilometer: return baseUnitValue/1e9; + case VolumeUnit.CubicMeter: return baseUnitValue; + case VolumeUnit.CubicMicrometer: return baseUnitValue*1e18; + case VolumeUnit.CubicMile: return baseUnitValue/(4.16818183*1e9); + case VolumeUnit.CubicMillimeter: return baseUnitValue*1e9; + case VolumeUnit.CubicYard: return baseUnitValue/0.764554858; + case VolumeUnit.Deciliter: return (baseUnitValue*1e3) / 1e-1d; + case VolumeUnit.HectocubicFoot: return (baseUnitValue/0.0283168) / 1e2d; + case VolumeUnit.HectocubicMeter: return (baseUnitValue) / 1e2d; + case VolumeUnit.Hectoliter: return (baseUnitValue*1e3) / 1e2d; + case VolumeUnit.ImperialBeerBarrel: return baseUnitValue/0.16365924; + case VolumeUnit.ImperialGallon: return baseUnitValue/0.00454609000000181429905810072407; + case VolumeUnit.ImperialOunce: return baseUnitValue/2.8413062499962901241875439064617e-5; + case VolumeUnit.KilocubicFoot: return (baseUnitValue/0.0283168) / 1e3d; + case VolumeUnit.KilocubicMeter: return (baseUnitValue) / 1e3d; + case VolumeUnit.KiloimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e3d; + case VolumeUnit.KilousGallon: return (baseUnitValue/0.00378541) / 1e3d; + case VolumeUnit.Liter: return baseUnitValue*1e3; + case VolumeUnit.MegacubicFoot: return (baseUnitValue/0.0283168) / 1e6d; + case VolumeUnit.MegaimperialGallon: return (baseUnitValue/0.00454609000000181429905810072407) / 1e6d; + case VolumeUnit.MegausGallon: return (baseUnitValue/0.00378541) / 1e6d; + case VolumeUnit.MetricCup: return baseUnitValue/0.00025; + case VolumeUnit.MetricTeaspoon: return baseUnitValue/0.5e-5; + case VolumeUnit.Microliter: return (baseUnitValue*1e3) / 1e-6d; + case VolumeUnit.Milliliter: return (baseUnitValue*1e3) / 1e-3d; + case VolumeUnit.OilBarrel: return baseUnitValue/0.158987294928; + case VolumeUnit.Tablespoon: return baseUnitValue/1.478676478125e-5; + case VolumeUnit.Teaspoon: return baseUnitValue/4.92892159375e-6; + case VolumeUnit.UkTablespoon: return baseUnitValue/1.5e-5; + case VolumeUnit.UsBeerBarrel: return baseUnitValue/0.1173477658; + case VolumeUnit.UsCustomaryCup: return baseUnitValue/0.0002365882365; + case VolumeUnit.UsGallon: return baseUnitValue/0.00378541; + case VolumeUnit.UsLegalCup: return baseUnitValue/0.00024; + case VolumeUnit.UsOunce: return baseUnitValue/2.957352956253760505068307980135e-5; + case VolumeUnit.UsTablespoon: return baseUnitValue/1.478676478125e-5; + case VolumeUnit.UsTeaspoon: return baseUnitValue/4.92892159375e-6; default: throw new NotImplementedException("unit: " + unit); @@ -2370,7 +1869,11 @@ public static Volume Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -2389,17 +1892,24 @@ public static Volume Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static Volume Parse(string str, [CanBeNull] Culture culture) + public static Volume Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -2425,16 +1935,41 @@ public static bool TryParse([CanBeNull] string str, out Volume result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out Volume result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out Volume result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -2447,6 +1982,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -2460,11 +1996,14 @@ public static VolumeUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static VolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -2473,6 +2012,8 @@ public static VolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -2485,18 +2026,18 @@ public static VolumeUnit ParseUnit(string str, [CanBeNull] string cultureName) #else public #endif - static VolumeUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static VolumeUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == VolumeUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VolumeUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -2505,6 +2046,7 @@ static VolumeUnit ParseUnit(string str, IFormatProvider formatProvider = null) #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is CubicMeter /// @@ -2516,7 +2058,7 @@ static VolumeUnit ParseUnit(string str, IFormatProvider formatProvider = null) /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -2533,74 +2075,170 @@ public string ToString(VolumeUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(VolumeUnit unit, [CanBeNull] Culture culture) + public string ToString( + VolumeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(VolumeUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + VolumeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(VolumeUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + VolumeUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of Volume /// - public static Volume MaxValue - { - get - { - return new Volume(double.MaxValue); - } - } + public static Volume MaxValue => new Volume(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of Volume /// - public static Volume MinValue - { - get - { - return new Volume(double.MinValue); - } - } - } + public static Volume MinValue => new Volume(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitCubicMeters() + { + if (Unit == VolumeUnit.CubicMeter) { return _value; } + + switch (Unit) + { + case VolumeUnit.AuTablespoon: return _value*2e-5; + case VolumeUnit.Centiliter: return (_value/1e3) * 1e-2d; + case VolumeUnit.CubicCentimeter: return _value/1e6; + case VolumeUnit.CubicDecimeter: return _value/1e3; + case VolumeUnit.CubicFoot: return _value*0.0283168; + case VolumeUnit.CubicInch: return _value*1.6387*1e-5; + case VolumeUnit.CubicKilometer: return _value*1e9; + case VolumeUnit.CubicMeter: return _value; + case VolumeUnit.CubicMicrometer: return _value/1e18; + case VolumeUnit.CubicMile: return _value*4.16818183*1e9; + case VolumeUnit.CubicMillimeter: return _value/1e9; + case VolumeUnit.CubicYard: return _value*0.764554858; + case VolumeUnit.Deciliter: return (_value/1e3) * 1e-1d; + case VolumeUnit.HectocubicFoot: return (_value*0.0283168) * 1e2d; + case VolumeUnit.HectocubicMeter: return (_value) * 1e2d; + case VolumeUnit.Hectoliter: return (_value/1e3) * 1e2d; + case VolumeUnit.ImperialBeerBarrel: return _value*0.16365924; + case VolumeUnit.ImperialGallon: return _value*0.00454609000000181429905810072407; + case VolumeUnit.ImperialOunce: return _value*2.8413062499962901241875439064617e-5; + case VolumeUnit.KilocubicFoot: return (_value*0.0283168) * 1e3d; + case VolumeUnit.KilocubicMeter: return (_value) * 1e3d; + case VolumeUnit.KiloimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e3d; + case VolumeUnit.KilousGallon: return (_value*0.00378541) * 1e3d; + case VolumeUnit.Liter: return _value/1e3; + case VolumeUnit.MegacubicFoot: return (_value*0.0283168) * 1e6d; + case VolumeUnit.MegaimperialGallon: return (_value*0.00454609000000181429905810072407) * 1e6d; + case VolumeUnit.MegausGallon: return (_value*0.00378541) * 1e6d; + case VolumeUnit.MetricCup: return _value*0.00025; + case VolumeUnit.MetricTeaspoon: return _value*0.5e-5; + case VolumeUnit.Microliter: return (_value/1e3) * 1e-6d; + case VolumeUnit.Milliliter: return (_value/1e3) * 1e-3d; + case VolumeUnit.OilBarrel: return _value*0.158987294928; + case VolumeUnit.Tablespoon: return _value*1.478676478125e-5; + case VolumeUnit.Teaspoon: return _value*4.92892159375e-6; + case VolumeUnit.UkTablespoon: return _value*1.5e-5; + case VolumeUnit.UsBeerBarrel: return _value*0.1173477658; + case VolumeUnit.UsCustomaryCup: return _value*0.0002365882365; + case VolumeUnit.UsGallon: return _value*0.00378541; + case VolumeUnit.UsLegalCup: return _value*0.00024; + case VolumeUnit.UsOunce: return _value*2.957352956253760505068307980135e-5; + case VolumeUnit.UsTablespoon: return _value*1.478676478125e-5; + case VolumeUnit.UsTeaspoon: return _value*4.92892159375e-6; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(VolumeUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs index 32e7dfd31b..680bbca448 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs @@ -44,13 +44,6 @@ using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -70,44 +63,88 @@ public partial struct VolumeFlow : IComparable, IComparable #endif { /// - /// Base unit of VolumeFlow. + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly VolumeFlowUnit? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly double _cubicMetersPerSecond; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public double Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public VolumeFlow() : this(0) + public VolumeFlow() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public VolumeFlow(double cubicmeterspersecond) { - _cubicMetersPerSecond = Convert.ToDouble(cubicmeterspersecond); + _value = Convert.ToDouble(cubicmeterspersecond); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + VolumeFlow(double numericValue, VolumeFlowUnit unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit CubicMeterPerSecond. + /// + /// Value assuming base unit CubicMeterPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - VolumeFlow(long cubicmeterspersecond) - { - _cubicMetersPerSecond = Convert.ToDouble(cubicmeterspersecond); - } + VolumeFlow(long cubicmeterspersecond) : this(Convert.ToDouble(cubicmeterspersecond), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit CubicMeterPerSecond. + /// + /// Value assuming base unit CubicMeterPerSecond. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - VolumeFlow(decimal cubicmeterspersecond) - { - _cubicMetersPerSecond = Convert.ToDouble(cubicmeterspersecond); - } + VolumeFlow(decimal cubicmeterspersecond) : this(Convert.ToDouble(cubicmeterspersecond), BaseUnit) { } #region Properties @@ -119,216 +156,114 @@ public VolumeFlow(double cubicmeterspersecond) /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static VolumeFlowUnit BaseUnit - { - get { return VolumeFlowUnit.CubicMeterPerSecond; } - } + public static VolumeFlowUnit BaseUnit => VolumeFlowUnit.CubicMeterPerSecond; /// /// All units of measurement for the VolumeFlow quantity. /// public static VolumeFlowUnit[] Units { get; } = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().ToArray(); - /// /// Get VolumeFlow in CentilitersPerMinute. /// - public double CentilitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e-2d; } - } - + public double CentilitersPerMinute => As(VolumeFlowUnit.CentilitersPerMinute); /// /// Get VolumeFlow in CubicDecimetersPerMinute. /// - public double CubicDecimetersPerMinute - { - get { return _cubicMetersPerSecond*60000.00000; } - } - + public double CubicDecimetersPerMinute => As(VolumeFlowUnit.CubicDecimeterPerMinute); /// /// Get VolumeFlow in CubicFeetPerHour. /// - public double CubicFeetPerHour - { - get { return _cubicMetersPerSecond/7.8657907199999087346816086183876e-6; } - } - + public double CubicFeetPerHour => As(VolumeFlowUnit.CubicFootPerHour); /// /// Get VolumeFlow in CubicFeetPerMinute. /// - public double CubicFeetPerMinute - { - get { return _cubicMetersPerSecond*2118.88000326; } - } - + public double CubicFeetPerMinute => As(VolumeFlowUnit.CubicFootPerMinute); /// /// Get VolumeFlow in CubicFeetPerSecond. /// - public double CubicFeetPerSecond - { - get { return _cubicMetersPerSecond*35.314666721; } - } - + public double CubicFeetPerSecond => As(VolumeFlowUnit.CubicFootPerSecond); /// /// Get VolumeFlow in CubicMetersPerHour. /// - public double CubicMetersPerHour - { - get { return _cubicMetersPerSecond*3600; } - } - + public double CubicMetersPerHour => As(VolumeFlowUnit.CubicMeterPerHour); /// /// Get VolumeFlow in CubicMetersPerMinute. /// - public double CubicMetersPerMinute - { - get { return _cubicMetersPerSecond*60; } - } - + public double CubicMetersPerMinute => As(VolumeFlowUnit.CubicMeterPerMinute); /// /// Get VolumeFlow in CubicMetersPerSecond. /// - public double CubicMetersPerSecond - { - get { return _cubicMetersPerSecond; } - } - + public double CubicMetersPerSecond => As(VolumeFlowUnit.CubicMeterPerSecond); /// /// Get VolumeFlow in CubicYardsPerHour. /// - public double CubicYardsPerHour - { - get { return _cubicMetersPerSecond/2.1237634944E-4; } - } - + public double CubicYardsPerHour => As(VolumeFlowUnit.CubicYardPerHour); /// /// Get VolumeFlow in CubicYardsPerMinute. /// - public double CubicYardsPerMinute - { - get { return _cubicMetersPerSecond/0.0127425809664; } - } - + public double CubicYardsPerMinute => As(VolumeFlowUnit.CubicYardPerMinute); /// /// Get VolumeFlow in CubicYardsPerSecond. /// - public double CubicYardsPerSecond - { - get { return _cubicMetersPerSecond/0.764554857984; } - } - + public double CubicYardsPerSecond => As(VolumeFlowUnit.CubicYardPerSecond); /// /// Get VolumeFlow in DecilitersPerMinute. /// - public double DecilitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e-1d; } - } - + public double DecilitersPerMinute => As(VolumeFlowUnit.DecilitersPerMinute); /// /// Get VolumeFlow in KilolitersPerMinute. /// - public double KilolitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e3d; } - } - + public double KilolitersPerMinute => As(VolumeFlowUnit.KilolitersPerMinute); /// /// Get VolumeFlow in LitersPerHour. /// - public double LitersPerHour - { - get { return _cubicMetersPerSecond*3600000.000; } - } - + public double LitersPerHour => As(VolumeFlowUnit.LitersPerHour); /// /// Get VolumeFlow in LitersPerMinute. /// - public double LitersPerMinute - { - get { return _cubicMetersPerSecond*60000.00000; } - } - + public double LitersPerMinute => As(VolumeFlowUnit.LitersPerMinute); /// /// Get VolumeFlow in LitersPerSecond. /// - public double LitersPerSecond - { - get { return _cubicMetersPerSecond*1000; } - } - + public double LitersPerSecond => As(VolumeFlowUnit.LitersPerSecond); /// /// Get VolumeFlow in MicrolitersPerMinute. /// - public double MicrolitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e-6d; } - } - + public double MicrolitersPerMinute => As(VolumeFlowUnit.MicrolitersPerMinute); /// /// Get VolumeFlow in MillilitersPerMinute. /// - public double MillilitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e-3d; } - } - + public double MillilitersPerMinute => As(VolumeFlowUnit.MillilitersPerMinute); /// /// Get VolumeFlow in MillionUsGallonsPerDay. /// - public double MillionUsGallonsPerDay - { - get { return _cubicMetersPerSecond*22.824465227; } - } - + public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonsPerDay); /// /// Get VolumeFlow in NanolitersPerMinute. /// - public double NanolitersPerMinute - { - get { return (_cubicMetersPerSecond*60000.00000) / 1e-9d; } - } - + public double NanolitersPerMinute => As(VolumeFlowUnit.NanolitersPerMinute); /// /// Get VolumeFlow in OilBarrelsPerDay. /// - public double OilBarrelsPerDay - { - get { return _cubicMetersPerSecond/1.8401307283333333333333333333333e-6; } - } - + public double OilBarrelsPerDay => As(VolumeFlowUnit.OilBarrelsPerDay); /// /// Get VolumeFlow in UsGallonsPerHour. /// - public double UsGallonsPerHour - { - get { return _cubicMetersPerSecond*951019.38848933424; } - } - + public double UsGallonsPerHour => As(VolumeFlowUnit.UsGallonsPerHour); /// /// Get VolumeFlow in UsGallonsPerMinute. /// - public double UsGallonsPerMinute - { - get { return _cubicMetersPerSecond*15850.323141489; } - } - + public double UsGallonsPerMinute => As(VolumeFlowUnit.UsGallonsPerMinute); /// /// Get VolumeFlow in UsGallonsPerSecond. /// - public double UsGallonsPerSecond - { - get { return _cubicMetersPerSecond*264.1720523581484; } - } + public double UsGallonsPerSecond => As(VolumeFlowUnit.UsGallonsPerSecond); #endregion #region Static - public static VolumeFlow Zero - { - get { return new VolumeFlow(); } - } + public static VolumeFlow Zero => new VolumeFlow(0, BaseUnit); /// /// Get VolumeFlow from CentilitersPerMinute. @@ -336,17 +271,13 @@ public static VolumeFlow Zero #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCentilitersPerMinute(double centilitersperminute) - { - double value = (double) centilitersperminute; - return new VolumeFlow((value/60000.00000) * 1e-2d); - } #else public static VolumeFlow FromCentilitersPerMinute(QuantityValue centilitersperminute) +#endif { double value = (double) centilitersperminute; - return new VolumeFlow(((value/60000.00000) * 1e-2d)); + return new VolumeFlow(value, VolumeFlowUnit.CentilitersPerMinute); } -#endif /// /// Get VolumeFlow from CubicDecimetersPerMinute. @@ -354,17 +285,13 @@ public static VolumeFlow FromCentilitersPerMinute(QuantityValue centiliterspermi #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCubicDecimetersPerMinute(double cubicdecimetersperminute) - { - double value = (double) cubicdecimetersperminute; - return new VolumeFlow(value/60000.00000); - } #else public static VolumeFlow FromCubicDecimetersPerMinute(QuantityValue cubicdecimetersperminute) +#endif { double value = (double) cubicdecimetersperminute; - return new VolumeFlow((value/60000.00000)); + return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); } -#endif /// /// Get VolumeFlow from CubicFeetPerHour. @@ -372,17 +299,13 @@ public static VolumeFlow FromCubicDecimetersPerMinute(QuantityValue cubicdecimet #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCubicFeetPerHour(double cubicfeetperhour) - { - double value = (double) cubicfeetperhour; - return new VolumeFlow(value*7.8657907199999087346816086183876e-6); - } #else public static VolumeFlow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) +#endif { double value = (double) cubicfeetperhour; - return new VolumeFlow((value*7.8657907199999087346816086183876e-6)); + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); } -#endif /// /// Get VolumeFlow from CubicFeetPerMinute. @@ -390,17 +313,13 @@ public static VolumeFlow FromCubicFeetPerHour(QuantityValue cubicfeetperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCubicFeetPerMinute(double cubicfeetperminute) - { - double value = (double) cubicfeetperminute; - return new VolumeFlow(value/2118.88000326); - } #else public static VolumeFlow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute) +#endif { double value = (double) cubicfeetperminute; - return new VolumeFlow((value/2118.88000326)); + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); } -#endif /// /// Get VolumeFlow from CubicFeetPerSecond. @@ -408,17 +327,13 @@ public static VolumeFlow FromCubicFeetPerMinute(QuantityValue cubicfeetperminute #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCubicFeetPerSecond(double cubicfeetpersecond) - { - double value = (double) cubicfeetpersecond; - return new VolumeFlow(value/35.314666721); - } #else public static VolumeFlow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond) +#endif { double value = (double) cubicfeetpersecond; - return new VolumeFlow((value/35.314666721)); + return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); } -#endif /// /// Get VolumeFlow from CubicMetersPerHour. @@ -426,17 +341,13 @@ public static VolumeFlow FromCubicFeetPerSecond(QuantityValue cubicfeetpersecond #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCubicMetersPerHour(double cubicmetersperhour) - { - double value = (double) cubicmetersperhour; - return new VolumeFlow(value/3600); - } #else public static VolumeFlow FromCubicMetersPerHour(QuantityValue cubicmetersperhour) +#endif { double value = (double) cubicmetersperhour; - return new VolumeFlow((value/3600)); + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); } -#endif /// /// Get VolumeFlow from CubicMetersPerMinute. @@ -444,17 +355,13 @@ public static VolumeFlow FromCubicMetersPerHour(QuantityValue cubicmetersperhour #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCubicMetersPerMinute(double cubicmetersperminute) - { - double value = (double) cubicmetersperminute; - return new VolumeFlow(value/60); - } #else public static VolumeFlow FromCubicMetersPerMinute(QuantityValue cubicmetersperminute) +#endif { double value = (double) cubicmetersperminute; - return new VolumeFlow((value/60)); + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); } -#endif /// /// Get VolumeFlow from CubicMetersPerSecond. @@ -462,17 +369,13 @@ public static VolumeFlow FromCubicMetersPerMinute(QuantityValue cubicmeterspermi #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCubicMetersPerSecond(double cubicmeterspersecond) - { - double value = (double) cubicmeterspersecond; - return new VolumeFlow(value); - } #else public static VolumeFlow FromCubicMetersPerSecond(QuantityValue cubicmeterspersecond) +#endif { double value = (double) cubicmeterspersecond; - return new VolumeFlow((value)); + return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); } -#endif /// /// Get VolumeFlow from CubicYardsPerHour. @@ -480,17 +383,13 @@ public static VolumeFlow FromCubicMetersPerSecond(QuantityValue cubicmetersperse #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCubicYardsPerHour(double cubicyardsperhour) - { - double value = (double) cubicyardsperhour; - return new VolumeFlow(value*2.1237634944E-4); - } #else public static VolumeFlow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) +#endif { double value = (double) cubicyardsperhour; - return new VolumeFlow((value*2.1237634944E-4)); + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); } -#endif /// /// Get VolumeFlow from CubicYardsPerMinute. @@ -498,17 +397,13 @@ public static VolumeFlow FromCubicYardsPerHour(QuantityValue cubicyardsperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCubicYardsPerMinute(double cubicyardsperminute) - { - double value = (double) cubicyardsperminute; - return new VolumeFlow(value*0.0127425809664); - } #else public static VolumeFlow FromCubicYardsPerMinute(QuantityValue cubicyardsperminute) +#endif { double value = (double) cubicyardsperminute; - return new VolumeFlow((value*0.0127425809664)); + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); } -#endif /// /// Get VolumeFlow from CubicYardsPerSecond. @@ -516,17 +411,13 @@ public static VolumeFlow FromCubicYardsPerMinute(QuantityValue cubicyardsperminu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromCubicYardsPerSecond(double cubicyardspersecond) - { - double value = (double) cubicyardspersecond; - return new VolumeFlow(value*0.764554857984); - } #else public static VolumeFlow FromCubicYardsPerSecond(QuantityValue cubicyardspersecond) +#endif { double value = (double) cubicyardspersecond; - return new VolumeFlow((value*0.764554857984)); + return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); } -#endif /// /// Get VolumeFlow from DecilitersPerMinute. @@ -534,17 +425,13 @@ public static VolumeFlow FromCubicYardsPerSecond(QuantityValue cubicyardsperseco #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromDecilitersPerMinute(double decilitersperminute) - { - double value = (double) decilitersperminute; - return new VolumeFlow((value/60000.00000) * 1e-1d); - } #else public static VolumeFlow FromDecilitersPerMinute(QuantityValue decilitersperminute) +#endif { double value = (double) decilitersperminute; - return new VolumeFlow(((value/60000.00000) * 1e-1d)); + return new VolumeFlow(value, VolumeFlowUnit.DecilitersPerMinute); } -#endif /// /// Get VolumeFlow from KilolitersPerMinute. @@ -552,17 +439,13 @@ public static VolumeFlow FromDecilitersPerMinute(QuantityValue decilitersperminu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromKilolitersPerMinute(double kilolitersperminute) - { - double value = (double) kilolitersperminute; - return new VolumeFlow((value/60000.00000) * 1e3d); - } #else public static VolumeFlow FromKilolitersPerMinute(QuantityValue kilolitersperminute) +#endif { double value = (double) kilolitersperminute; - return new VolumeFlow(((value/60000.00000) * 1e3d)); + return new VolumeFlow(value, VolumeFlowUnit.KilolitersPerMinute); } -#endif /// /// Get VolumeFlow from LitersPerHour. @@ -570,17 +453,13 @@ public static VolumeFlow FromKilolitersPerMinute(QuantityValue kilolitersperminu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromLitersPerHour(double litersperhour) - { - double value = (double) litersperhour; - return new VolumeFlow(value/3600000.000); - } #else public static VolumeFlow FromLitersPerHour(QuantityValue litersperhour) +#endif { double value = (double) litersperhour; - return new VolumeFlow((value/3600000.000)); + return new VolumeFlow(value, VolumeFlowUnit.LitersPerHour); } -#endif /// /// Get VolumeFlow from LitersPerMinute. @@ -588,17 +467,13 @@ public static VolumeFlow FromLitersPerHour(QuantityValue litersperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromLitersPerMinute(double litersperminute) - { - double value = (double) litersperminute; - return new VolumeFlow(value/60000.00000); - } #else public static VolumeFlow FromLitersPerMinute(QuantityValue litersperminute) +#endif { double value = (double) litersperminute; - return new VolumeFlow((value/60000.00000)); + return new VolumeFlow(value, VolumeFlowUnit.LitersPerMinute); } -#endif /// /// Get VolumeFlow from LitersPerSecond. @@ -606,17 +481,13 @@ public static VolumeFlow FromLitersPerMinute(QuantityValue litersperminute) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromLitersPerSecond(double literspersecond) - { - double value = (double) literspersecond; - return new VolumeFlow(value/1000); - } #else public static VolumeFlow FromLitersPerSecond(QuantityValue literspersecond) +#endif { double value = (double) literspersecond; - return new VolumeFlow((value/1000)); + return new VolumeFlow(value, VolumeFlowUnit.LitersPerSecond); } -#endif /// /// Get VolumeFlow from MicrolitersPerMinute. @@ -624,17 +495,13 @@ public static VolumeFlow FromLitersPerSecond(QuantityValue literspersecond) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromMicrolitersPerMinute(double microlitersperminute) - { - double value = (double) microlitersperminute; - return new VolumeFlow((value/60000.00000) * 1e-6d); - } #else public static VolumeFlow FromMicrolitersPerMinute(QuantityValue microlitersperminute) +#endif { double value = (double) microlitersperminute; - return new VolumeFlow(((value/60000.00000) * 1e-6d)); + return new VolumeFlow(value, VolumeFlowUnit.MicrolitersPerMinute); } -#endif /// /// Get VolumeFlow from MillilitersPerMinute. @@ -642,17 +509,13 @@ public static VolumeFlow FromMicrolitersPerMinute(QuantityValue microliterspermi #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromMillilitersPerMinute(double millilitersperminute) - { - double value = (double) millilitersperminute; - return new VolumeFlow((value/60000.00000) * 1e-3d); - } #else public static VolumeFlow FromMillilitersPerMinute(QuantityValue millilitersperminute) +#endif { double value = (double) millilitersperminute; - return new VolumeFlow(((value/60000.00000) * 1e-3d)); + return new VolumeFlow(value, VolumeFlowUnit.MillilitersPerMinute); } -#endif /// /// Get VolumeFlow from MillionUsGallonsPerDay. @@ -660,17 +523,13 @@ public static VolumeFlow FromMillilitersPerMinute(QuantityValue milliliterspermi #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromMillionUsGallonsPerDay(double millionusgallonsperday) - { - double value = (double) millionusgallonsperday; - return new VolumeFlow(value/22.824465227); - } #else public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue millionusgallonsperday) +#endif { double value = (double) millionusgallonsperday; - return new VolumeFlow((value/22.824465227)); + return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonsPerDay); } -#endif /// /// Get VolumeFlow from NanolitersPerMinute. @@ -678,17 +537,13 @@ public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue millionusgallo #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromNanolitersPerMinute(double nanolitersperminute) - { - double value = (double) nanolitersperminute; - return new VolumeFlow((value/60000.00000) * 1e-9d); - } #else public static VolumeFlow FromNanolitersPerMinute(QuantityValue nanolitersperminute) +#endif { double value = (double) nanolitersperminute; - return new VolumeFlow(((value/60000.00000) * 1e-9d)); + return new VolumeFlow(value, VolumeFlowUnit.NanolitersPerMinute); } -#endif /// /// Get VolumeFlow from OilBarrelsPerDay. @@ -696,17 +551,13 @@ public static VolumeFlow FromNanolitersPerMinute(QuantityValue nanolitersperminu #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromOilBarrelsPerDay(double oilbarrelsperday) - { - double value = (double) oilbarrelsperday; - return new VolumeFlow(value*1.8401307283333333333333333333333e-6); - } #else public static VolumeFlow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) +#endif { double value = (double) oilbarrelsperday; - return new VolumeFlow((value*1.8401307283333333333333333333333e-6)); + return new VolumeFlow(value, VolumeFlowUnit.OilBarrelsPerDay); } -#endif /// /// Get VolumeFlow from UsGallonsPerHour. @@ -714,17 +565,13 @@ public static VolumeFlow FromOilBarrelsPerDay(QuantityValue oilbarrelsperday) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromUsGallonsPerHour(double usgallonsperhour) - { - double value = (double) usgallonsperhour; - return new VolumeFlow(value/951019.38848933424); - } #else public static VolumeFlow FromUsGallonsPerHour(QuantityValue usgallonsperhour) +#endif { double value = (double) usgallonsperhour; - return new VolumeFlow((value/951019.38848933424)); + return new VolumeFlow(value, VolumeFlowUnit.UsGallonsPerHour); } -#endif /// /// Get VolumeFlow from UsGallonsPerMinute. @@ -732,17 +579,13 @@ public static VolumeFlow FromUsGallonsPerHour(QuantityValue usgallonsperhour) #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromUsGallonsPerMinute(double usgallonsperminute) - { - double value = (double) usgallonsperminute; - return new VolumeFlow(value/15850.323141489); - } #else public static VolumeFlow FromUsGallonsPerMinute(QuantityValue usgallonsperminute) +#endif { double value = (double) usgallonsperminute; - return new VolumeFlow((value/15850.323141489)); + return new VolumeFlow(value, VolumeFlowUnit.UsGallonsPerMinute); } -#endif /// /// Get VolumeFlow from UsGallonsPerSecond. @@ -750,17 +593,13 @@ public static VolumeFlow FromUsGallonsPerMinute(QuantityValue usgallonsperminute #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static VolumeFlow FromUsGallonsPerSecond(double usgallonspersecond) - { - double value = (double) usgallonspersecond; - return new VolumeFlow(value/264.1720523581484); - } #else public static VolumeFlow FromUsGallonsPerSecond(QuantityValue usgallonspersecond) +#endif { double value = (double) usgallonspersecond; - return new VolumeFlow((value/264.1720523581484)); + return new VolumeFlow(value, VolumeFlowUnit.UsGallonsPerSecond); } -#endif // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP @@ -1140,60 +979,7 @@ public static VolumeFlow From(double value, VolumeFlowUnit fromUnit) public static VolumeFlow From(QuantityValue value, VolumeFlowUnit fromUnit) #endif { - switch (fromUnit) - { - case VolumeFlowUnit.CentilitersPerMinute: - return FromCentilitersPerMinute(value); - case VolumeFlowUnit.CubicDecimeterPerMinute: - return FromCubicDecimetersPerMinute(value); - case VolumeFlowUnit.CubicFootPerHour: - return FromCubicFeetPerHour(value); - case VolumeFlowUnit.CubicFootPerMinute: - return FromCubicFeetPerMinute(value); - case VolumeFlowUnit.CubicFootPerSecond: - return FromCubicFeetPerSecond(value); - case VolumeFlowUnit.CubicMeterPerHour: - return FromCubicMetersPerHour(value); - case VolumeFlowUnit.CubicMeterPerMinute: - return FromCubicMetersPerMinute(value); - case VolumeFlowUnit.CubicMeterPerSecond: - return FromCubicMetersPerSecond(value); - case VolumeFlowUnit.CubicYardPerHour: - return FromCubicYardsPerHour(value); - case VolumeFlowUnit.CubicYardPerMinute: - return FromCubicYardsPerMinute(value); - case VolumeFlowUnit.CubicYardPerSecond: - return FromCubicYardsPerSecond(value); - case VolumeFlowUnit.DecilitersPerMinute: - return FromDecilitersPerMinute(value); - case VolumeFlowUnit.KilolitersPerMinute: - return FromKilolitersPerMinute(value); - case VolumeFlowUnit.LitersPerHour: - return FromLitersPerHour(value); - case VolumeFlowUnit.LitersPerMinute: - return FromLitersPerMinute(value); - case VolumeFlowUnit.LitersPerSecond: - return FromLitersPerSecond(value); - case VolumeFlowUnit.MicrolitersPerMinute: - return FromMicrolitersPerMinute(value); - case VolumeFlowUnit.MillilitersPerMinute: - return FromMillilitersPerMinute(value); - case VolumeFlowUnit.MillionUsGallonsPerDay: - return FromMillionUsGallonsPerDay(value); - case VolumeFlowUnit.NanolitersPerMinute: - return FromNanolitersPerMinute(value); - case VolumeFlowUnit.OilBarrelsPerDay: - return FromOilBarrelsPerDay(value); - case VolumeFlowUnit.UsGallonsPerHour: - return FromUsGallonsPerHour(value); - case VolumeFlowUnit.UsGallonsPerMinute: - return FromUsGallonsPerMinute(value); - case VolumeFlowUnit.UsGallonsPerSecond: - return FromUsGallonsPerSecond(value); - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new VolumeFlow((double)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -1210,60 +996,8 @@ public static VolumeFlow From(QuantityValue value, VolumeFlowUnit fromUnit) { return null; } - switch (fromUnit) - { - case VolumeFlowUnit.CentilitersPerMinute: - return FromCentilitersPerMinute(value.Value); - case VolumeFlowUnit.CubicDecimeterPerMinute: - return FromCubicDecimetersPerMinute(value.Value); - case VolumeFlowUnit.CubicFootPerHour: - return FromCubicFeetPerHour(value.Value); - case VolumeFlowUnit.CubicFootPerMinute: - return FromCubicFeetPerMinute(value.Value); - case VolumeFlowUnit.CubicFootPerSecond: - return FromCubicFeetPerSecond(value.Value); - case VolumeFlowUnit.CubicMeterPerHour: - return FromCubicMetersPerHour(value.Value); - case VolumeFlowUnit.CubicMeterPerMinute: - return FromCubicMetersPerMinute(value.Value); - case VolumeFlowUnit.CubicMeterPerSecond: - return FromCubicMetersPerSecond(value.Value); - case VolumeFlowUnit.CubicYardPerHour: - return FromCubicYardsPerHour(value.Value); - case VolumeFlowUnit.CubicYardPerMinute: - return FromCubicYardsPerMinute(value.Value); - case VolumeFlowUnit.CubicYardPerSecond: - return FromCubicYardsPerSecond(value.Value); - case VolumeFlowUnit.DecilitersPerMinute: - return FromDecilitersPerMinute(value.Value); - case VolumeFlowUnit.KilolitersPerMinute: - return FromKilolitersPerMinute(value.Value); - case VolumeFlowUnit.LitersPerHour: - return FromLitersPerHour(value.Value); - case VolumeFlowUnit.LitersPerMinute: - return FromLitersPerMinute(value.Value); - case VolumeFlowUnit.LitersPerSecond: - return FromLitersPerSecond(value.Value); - case VolumeFlowUnit.MicrolitersPerMinute: - return FromMicrolitersPerMinute(value.Value); - case VolumeFlowUnit.MillilitersPerMinute: - return FromMillilitersPerMinute(value.Value); - case VolumeFlowUnit.MillionUsGallonsPerDay: - return FromMillionUsGallonsPerDay(value.Value); - case VolumeFlowUnit.NanolitersPerMinute: - return FromNanolitersPerMinute(value.Value); - case VolumeFlowUnit.OilBarrelsPerDay: - return FromOilBarrelsPerDay(value.Value); - case VolumeFlowUnit.UsGallonsPerHour: - return FromUsGallonsPerHour(value.Value); - case VolumeFlowUnit.UsGallonsPerMinute: - return FromUsGallonsPerMinute(value.Value); - case VolumeFlowUnit.UsGallonsPerSecond: - return FromUsGallonsPerSecond(value.Value); - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new VolumeFlow((double)value.Value, fromUnit); } #endif @@ -1282,12 +1016,29 @@ public static string GetAbbreviation(VolumeFlowUnit unit) /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation(VolumeFlowUnit unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + VolumeFlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -1298,37 +1049,37 @@ public static string GetAbbreviation(VolumeFlowUnit unit, [CanBeNull] Culture cu #if !WINDOWS_UWP public static VolumeFlow operator -(VolumeFlow right) { - return new VolumeFlow(-right._cubicMetersPerSecond); + return new VolumeFlow(-right.Value, right.Unit); } public static VolumeFlow operator +(VolumeFlow left, VolumeFlow right) { - return new VolumeFlow(left._cubicMetersPerSecond + right._cubicMetersPerSecond); + return new VolumeFlow(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static VolumeFlow operator -(VolumeFlow left, VolumeFlow right) { - return new VolumeFlow(left._cubicMetersPerSecond - right._cubicMetersPerSecond); + return new VolumeFlow(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static VolumeFlow operator *(double left, VolumeFlow right) { - return new VolumeFlow(left*right._cubicMetersPerSecond); + return new VolumeFlow(left * right.Value, right.Unit); } public static VolumeFlow operator *(VolumeFlow left, double right) { - return new VolumeFlow(left._cubicMetersPerSecond*(double)right); + return new VolumeFlow(left.Value * right, left.Unit); } public static VolumeFlow operator /(VolumeFlow left, double right) { - return new VolumeFlow(left._cubicMetersPerSecond/(double)right); + return new VolumeFlow(left.Value / right, left.Unit); } public static double operator /(VolumeFlow left, VolumeFlow right) { - return Convert.ToDouble(left._cubicMetersPerSecond/right._cubicMetersPerSecond); + return left.CubicMetersPerSecond / right.CubicMetersPerSecond; } #endif @@ -1351,43 +1102,43 @@ public int CompareTo(object obj) #endif int CompareTo(VolumeFlow other) { - return _cubicMetersPerSecond.CompareTo(other._cubicMetersPerSecond); + return AsBaseUnitCubicMetersPerSecond().CompareTo(other.AsBaseUnitCubicMetersPerSecond()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=(VolumeFlow left, VolumeFlow right) { - return left._cubicMetersPerSecond <= right._cubicMetersPerSecond; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=(VolumeFlow left, VolumeFlow right) { - return left._cubicMetersPerSecond >= right._cubicMetersPerSecond; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <(VolumeFlow left, VolumeFlow right) { - return left._cubicMetersPerSecond < right._cubicMetersPerSecond; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >(VolumeFlow left, VolumeFlow right) { - return left._cubicMetersPerSecond > right._cubicMetersPerSecond; + return left.Value > right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator ==(VolumeFlow left, VolumeFlow right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._cubicMetersPerSecond == right._cubicMetersPerSecond; + return left.Value == right.AsBaseNumericType(left.Unit); } [Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")] public static bool operator !=(VolumeFlow left, VolumeFlow right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left._cubicMetersPerSecond != right._cubicMetersPerSecond; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -1399,7 +1150,7 @@ public override bool Equals(object obj) return false; } - return _cubicMetersPerSecond.Equals(((VolumeFlow) obj)._cubicMetersPerSecond); + return AsBaseUnitCubicMetersPerSecond().Equals(((VolumeFlow) obj).AsBaseUnitCubicMetersPerSecond()); } /// @@ -1412,12 +1163,12 @@ public override bool Equals(object obj) /// True if the difference between the two values is not greater than the specified max. public bool Equals(VolumeFlow other, VolumeFlow maxError) { - return Math.Abs(_cubicMetersPerSecond - other._cubicMetersPerSecond) <= maxError._cubicMetersPerSecond; + return Math.Abs(AsBaseUnitCubicMetersPerSecond() - other.AsBaseUnitCubicMetersPerSecond()) <= maxError.AsBaseUnitCubicMetersPerSecond(); } public override int GetHashCode() { - return _cubicMetersPerSecond.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -1427,60 +1178,42 @@ public override int GetHashCode() /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As(VolumeFlowUnit unit) { + if (Unit == unit) + { + return (double)Value; + } + + double baseUnitValue = AsBaseUnitCubicMetersPerSecond(); + switch (unit) { - case VolumeFlowUnit.CentilitersPerMinute: - return CentilitersPerMinute; - case VolumeFlowUnit.CubicDecimeterPerMinute: - return CubicDecimetersPerMinute; - case VolumeFlowUnit.CubicFootPerHour: - return CubicFeetPerHour; - case VolumeFlowUnit.CubicFootPerMinute: - return CubicFeetPerMinute; - case VolumeFlowUnit.CubicFootPerSecond: - return CubicFeetPerSecond; - case VolumeFlowUnit.CubicMeterPerHour: - return CubicMetersPerHour; - case VolumeFlowUnit.CubicMeterPerMinute: - return CubicMetersPerMinute; - case VolumeFlowUnit.CubicMeterPerSecond: - return CubicMetersPerSecond; - case VolumeFlowUnit.CubicYardPerHour: - return CubicYardsPerHour; - case VolumeFlowUnit.CubicYardPerMinute: - return CubicYardsPerMinute; - case VolumeFlowUnit.CubicYardPerSecond: - return CubicYardsPerSecond; - case VolumeFlowUnit.DecilitersPerMinute: - return DecilitersPerMinute; - case VolumeFlowUnit.KilolitersPerMinute: - return KilolitersPerMinute; - case VolumeFlowUnit.LitersPerHour: - return LitersPerHour; - case VolumeFlowUnit.LitersPerMinute: - return LitersPerMinute; - case VolumeFlowUnit.LitersPerSecond: - return LitersPerSecond; - case VolumeFlowUnit.MicrolitersPerMinute: - return MicrolitersPerMinute; - case VolumeFlowUnit.MillilitersPerMinute: - return MillilitersPerMinute; - case VolumeFlowUnit.MillionUsGallonsPerDay: - return MillionUsGallonsPerDay; - case VolumeFlowUnit.NanolitersPerMinute: - return NanolitersPerMinute; - case VolumeFlowUnit.OilBarrelsPerDay: - return OilBarrelsPerDay; - case VolumeFlowUnit.UsGallonsPerHour: - return UsGallonsPerHour; - case VolumeFlowUnit.UsGallonsPerMinute: - return UsGallonsPerMinute; - case VolumeFlowUnit.UsGallonsPerSecond: - return UsGallonsPerSecond; + case VolumeFlowUnit.CentilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-2d; + case VolumeFlowUnit.CubicDecimeterPerMinute: return baseUnitValue*60000.00000; + case VolumeFlowUnit.CubicFootPerHour: return baseUnitValue/7.8657907199999087346816086183876e-6; + case VolumeFlowUnit.CubicFootPerMinute: return baseUnitValue*2118.88000326; + case VolumeFlowUnit.CubicFootPerSecond: return baseUnitValue*35.314666721; + case VolumeFlowUnit.CubicMeterPerHour: return baseUnitValue*3600; + case VolumeFlowUnit.CubicMeterPerMinute: return baseUnitValue*60; + case VolumeFlowUnit.CubicMeterPerSecond: return baseUnitValue; + case VolumeFlowUnit.CubicYardPerHour: return baseUnitValue/2.1237634944E-4; + case VolumeFlowUnit.CubicYardPerMinute: return baseUnitValue/0.0127425809664; + case VolumeFlowUnit.CubicYardPerSecond: return baseUnitValue/0.764554857984; + case VolumeFlowUnit.DecilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-1d; + case VolumeFlowUnit.KilolitersPerMinute: return (baseUnitValue*60000.00000) / 1e3d; + case VolumeFlowUnit.LitersPerHour: return baseUnitValue*3600000.000; + case VolumeFlowUnit.LitersPerMinute: return baseUnitValue*60000.00000; + case VolumeFlowUnit.LitersPerSecond: return baseUnitValue*1000; + case VolumeFlowUnit.MicrolitersPerMinute: return (baseUnitValue*60000.00000) / 1e-6d; + case VolumeFlowUnit.MillilitersPerMinute: return (baseUnitValue*60000.00000) / 1e-3d; + case VolumeFlowUnit.MillionUsGallonsPerDay: return baseUnitValue*22.824465227; + case VolumeFlowUnit.NanolitersPerMinute: return (baseUnitValue*60000.00000) / 1e-9d; + case VolumeFlowUnit.OilBarrelsPerDay: return baseUnitValue/1.8401307283333333333333333333333e-6; + case VolumeFlowUnit.UsGallonsPerHour: return baseUnitValue*951019.38848933424; + case VolumeFlowUnit.UsGallonsPerMinute: return baseUnitValue*15850.323141489; + case VolumeFlowUnit.UsGallonsPerSecond: return baseUnitValue*264.1720523581484; default: throw new NotImplementedException("unit: " + unit); @@ -1522,7 +1255,11 @@ public static VolumeFlow Parse(string str) /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -1541,17 +1278,24 @@ public static VolumeFlow Parse(string str) /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static VolumeFlow Parse(string str, [CanBeNull] Culture culture) + public static VolumeFlow Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse(str, formatProvider, + + return QuantityParser.Parse(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -1577,16 +1321,41 @@ public static bool TryParse([CanBeNull] string str, out VolumeFlow result) /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out VolumeFlow result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out VolumeFlow result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -1599,6 +1368,7 @@ public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1612,11 +1382,14 @@ public static VolumeFlowUnit ParseUnit(string str) /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static VolumeFlowUnit ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -1625,6 +1398,8 @@ public static VolumeFlowUnit ParseUnit(string str, [CanBeNull] string cultureNam /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -1637,18 +1412,18 @@ public static VolumeFlowUnit ParseUnit(string str, [CanBeNull] string cultureNam #else public #endif - static VolumeFlowUnit ParseUnit(string str, IFormatProvider formatProvider = null) + static VolumeFlowUnit ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse(str.Trim()); if (unit == VolumeFlowUnit.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized VolumeFlowUnit."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -1657,6 +1432,7 @@ static VolumeFlowUnit ParseUnit(string str, IFormatProvider formatProvider = nul #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is CubicMeterPerSecond /// @@ -1668,7 +1444,7 @@ static VolumeFlowUnit ParseUnit(string str, IFormatProvider formatProvider = nul /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -1685,74 +1461,152 @@ public string ToString(VolumeFlowUnit unit) /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString(VolumeFlowUnit unit, [CanBeNull] Culture culture) + public string ToString( + VolumeFlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString(VolumeFlowUnit unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + VolumeFlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString(VolumeFlowUnit unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + VolumeFlowUnit unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of VolumeFlow /// - public static VolumeFlow MaxValue - { - get - { - return new VolumeFlow(double.MaxValue); - } - } + public static VolumeFlow MaxValue => new VolumeFlow(double.MaxValue, BaseUnit); /// /// Represents the smallest possible value of VolumeFlow /// - public static VolumeFlow MinValue + public static VolumeFlow MinValue => new VolumeFlow(double.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double AsBaseUnitCubicMetersPerSecond() { - get + if (Unit == VolumeFlowUnit.CubicMeterPerSecond) { return _value; } + + switch (Unit) { - return new VolumeFlow(double.MinValue); - } - } - } + case VolumeFlowUnit.CentilitersPerMinute: return (_value/60000.00000) * 1e-2d; + case VolumeFlowUnit.CubicDecimeterPerMinute: return _value/60000.00000; + case VolumeFlowUnit.CubicFootPerHour: return _value*7.8657907199999087346816086183876e-6; + case VolumeFlowUnit.CubicFootPerMinute: return _value/2118.88000326; + case VolumeFlowUnit.CubicFootPerSecond: return _value/35.314666721; + case VolumeFlowUnit.CubicMeterPerHour: return _value/3600; + case VolumeFlowUnit.CubicMeterPerMinute: return _value/60; + case VolumeFlowUnit.CubicMeterPerSecond: return _value; + case VolumeFlowUnit.CubicYardPerHour: return _value*2.1237634944E-4; + case VolumeFlowUnit.CubicYardPerMinute: return _value*0.0127425809664; + case VolumeFlowUnit.CubicYardPerSecond: return _value*0.764554857984; + case VolumeFlowUnit.DecilitersPerMinute: return (_value/60000.00000) * 1e-1d; + case VolumeFlowUnit.KilolitersPerMinute: return (_value/60000.00000) * 1e3d; + case VolumeFlowUnit.LitersPerHour: return _value/3600000.000; + case VolumeFlowUnit.LitersPerMinute: return _value/60000.00000; + case VolumeFlowUnit.LitersPerSecond: return _value/1000; + case VolumeFlowUnit.MicrolitersPerMinute: return (_value/60000.00000) * 1e-6d; + case VolumeFlowUnit.MillilitersPerMinute: return (_value/60000.00000) * 1e-3d; + case VolumeFlowUnit.MillionUsGallonsPerDay: return _value/22.824465227; + case VolumeFlowUnit.NanolitersPerMinute: return (_value/60000.00000) * 1e-9d; + case VolumeFlowUnit.OilBarrelsPerDay: return _value*1.8401307283333333333333333333333e-6; + case VolumeFlowUnit.UsGallonsPerHour: return _value/951019.38848933424; + case VolumeFlowUnit.UsGallonsPerMinute: return _value/15850.323141489; + case VolumeFlowUnit.UsGallonsPerSecond: return _value/264.1720523581484; + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private double AsBaseNumericType(VolumeFlowUnit unit) => Convert.ToDouble(As(unit)); + } } diff --git a/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs b/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs index 5a15193a2a..6334dbb399 100644 --- a/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs +++ b/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs @@ -19,11 +19,17 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +using System.Runtime.CompilerServices; using System; using System.Collections.Generic; -//using System.Linq; using System.Reflection; +#if SIGNED +[assembly: InternalsVisibleTo("UnitsNet.Serialization.JsonNet, PublicKey=002400000480000094000000060200000024000052534131000400000100010089abdcb0025f7d1c4c766686dd852b978ca5bb9fd80bba9d3539e8399b01170ae0ea10c0c3baa301b1d13090d5aff770532de00c88b67c4b24669fde7f9d87218f1c6c073a09016cbb2f87119b94227c2301f4e2a096043e30f7c47c872bbd8e0b80d924952e6b36990f13f847e83e9efb107ec2121fe39d7edaaa4e235af8c4")] +#else +[assembly: InternalsVisibleTo("UnitsNet.Serialization.JsonNet")] +#endif + // Based on // https://github.com/StefH/ReflectionBridge/blob/c1e34e57fe3fc93507e83d5cebc1677396645397/ReflectionBridge/src/ReflectionBridge/Extensions/ReflectionBridgeExtensions.cs // MIT license @@ -205,8 +211,18 @@ internal static bool IsValueType(this Type type) //#endif // } + internal static PropertyInfo GetPropety(this Type type, string name) + { +#if (NET40 || NET35 || NET20 || SILVERLIGHT) + return type.GetProperty(name); + +#else + return type.GetTypeInfo().GetDeclaredProperty(name); +#endif + } + #if !(NET40 || NET35 || NET20 || SILVERLIGHT) - // Ambiguous method conflict with GetMethods() name WindowsRuntimeComponent, so use GetDeclaredMethods() instead + // Ambiguous method conflict with GetMethods() name when targeting WindowsRuntimeComponent, so use GetDeclaredMethods() instead internal static IEnumerable GetDeclaredMethods(this Type someType) { Type t = someType; @@ -245,7 +261,7 @@ internal static IEnumerable GetDeclaredMethods(this Type someType) // return type.GetTypeInfo().GetCustomAttributes(attributeType, inherit).Cast().ToArray(); // } #else - // Ambiguous method conflict with GetMethods() name WindowsRuntimeComponent, so use GetDeclaredMethods() instead +// Ambiguous method conflict with GetMethods() name WindowsRuntimeComponent, so use GetDeclaredMethods() instead internal static IEnumerable GetDeclaredMethods(this Type someType) { Type t = someType; @@ -258,4 +274,4 @@ internal static IEnumerable GetDeclaredMethods(this Type someType) } #endif } -} \ No newline at end of file +} diff --git a/UnitsNet/QuantityValue.cs b/UnitsNet/QuantityValue.cs index 7a972a10ec..c1f0960769 100644 --- a/UnitsNet/QuantityValue.cs +++ b/UnitsNet/QuantityValue.cs @@ -1,16 +1,16 @@ -// Copyright © 2007 Andreas Gullberg Larsen (angularsen@gmail.com). +// Copyright (c) 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). // https://github.com/angularsen/UnitsNet -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,49 +20,89 @@ // THE SOFTWARE. // Operator overloads not supported in Windows Runtime Components, we use 'double' type instead + #if !WINDOWS_UWP using System; namespace UnitsNet { /// - /// Pass it any numeric value (int, double, decimal, float..) and it will be implicitly converted to a , the quantity value representation used in UnitsNet. - /// This is used to avoid an explosion of overloads for methods taking N numeric types for all our 500+ units. + /// A type that supports implicit cast from all .NET numeric types, in order to avoid a large number of overloads + /// and binary size for all From(value, unit) factory methods, for each of the 700+ units in the library. + /// stores the value internally with the proper type to preserve the range or precision of the original value: + /// + /// for [byte, short, int, long, float, double] + /// for [decimal] to preserve the 128-bit precision + /// /// /// - /// At the time of this writing, this reduces the number of From() overloads to 1/4th: + /// At the time of this writing, this reduces the number of From(value, unit) overloads to 1/4th: /// From 8 (int, long, double, decimal + each nullable) down to 2 (QuantityValue and QuantityValue?). /// This also adds more numeric types with no extra overhead, such as float, short and byte. /// public struct QuantityValue { - private readonly double _value; + /// + /// Value assigned when implicitly casting from all numeric types except , since + /// has the greatest range and is 64 bits versus 128 bits for . + /// + private readonly double? _value; + + /// + /// Value assigned when implicitly casting from type, since it has a greater precision than + /// and we want to preserve that when constructing quantities that use + /// as their value type. + /// + private readonly decimal? _valueDecimal; - // Obsolete is used to communicate how they should use this type, instead of making the constructor private and have them figure it out - [Obsolete("Do not use this constructor. Instead pass any numeric value such as int, long, float, double, decimal, short or byte directly and it will be implicitly casted to double.")] private QuantityValue(double val) { _value = val; + _valueDecimal = null; + } + + private QuantityValue(decimal val) + { + _valueDecimal = val; + _value = null; } #region To QuantityValue #pragma warning disable 618 - public static implicit operator QuantityValue(double val) => new QuantityValue(val); - public static implicit operator QuantityValue(float val) => new QuantityValue(val); - public static implicit operator QuantityValue(long val) => new QuantityValue(val); - public static implicit operator QuantityValue(decimal val) => new QuantityValue(Convert.ToDouble(val)); - public static implicit operator QuantityValue(short val) => new QuantityValue(val); - public static implicit operator QuantityValue(byte val) => new QuantityValue(val); + // Prefer double for integer types, since most quantities use that type as of now and + // that avoids unnecessary casts back and forth. + // If we later change to use decimal more, we should revisit this. + public static implicit operator QuantityValue(byte val) => new QuantityValue((double) val); + public static implicit operator QuantityValue(short val) => new QuantityValue((double) val); + public static implicit operator QuantityValue(int val) => new QuantityValue((double) val); + public static implicit operator QuantityValue(long val) => new QuantityValue((double) val); + public static implicit operator QuantityValue(float val) => new QuantityValue(val); // double + public static implicit operator QuantityValue(double val) => new QuantityValue(val); // double + public static implicit operator QuantityValue(decimal val) => new QuantityValue(val); // decimal #pragma warning restore 618 - + #endregion #region To double - public static explicit operator double(QuantityValue number) => number._value; + public static explicit operator double(QuantityValue number) + { + // double -> decimal -> zero (since we can't implement the default struct ctor) + return number._value.GetValueOrDefault((double) number._valueDecimal.GetValueOrDefault()); + } + + #endregion + + #region To decimal + + public static explicit operator decimal(QuantityValue number) + { + // decimal -> double -> zero (since we can't implement the default struct ctor) + return number._valueDecimal.GetValueOrDefault((decimal) number._value.GetValueOrDefault()); + } #endregion } } -#endif \ No newline at end of file +#endif diff --git a/UnitsNet/Scripts/GenerateUnits.ps1 b/UnitsNet/Scripts/GenerateUnits.ps1 index 9f35ad2ad9..b66970f972 100644 --- a/UnitsNet/Scripts/GenerateUnits.ps1 +++ b/UnitsNet/Scripts/GenerateUnits.ps1 @@ -135,8 +135,8 @@ function Set-ConversionFunctions foreach ($u in $quantity.Units) { # Use decimal for internal calculations if base type is not double, such as for long or int. - if ($quantity.BaseType -ne "double") { - $u.FromUnitToBaseFunc = $u.FromUnitToBaseFunc -replace "m", "d" + if ($quantity.BaseType -eq "decimal") { + $u.FromUnitToBaseFunc = $u.FromUnitToBaseFunc -replace "d", "m" $u.FromBaseToUnitFunc = $u.FromBaseToUnitFunc -replace "d", "m" } @@ -274,8 +274,8 @@ $pad = 25 $quantities = Get-ChildItem -Path $templatesDir -filter "*.json" ` | %{(Get-Content $_.FullName -Encoding "UTF8" | Out-String)} ` | ConvertFrom-Json ` - | Add-PrefixUnits ` | Set-DefaultValues ` + | Add-PrefixUnits ` | Set-ConversionFunctions ` | Set-UnitsOrderedByName diff --git a/UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 b/UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 index ff1df9892e..410eed33ae 100644 --- a/UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 +++ b/UnitsNet/Scripts/Include-GenerateLogarithmicCode.ps1 @@ -28,45 +28,45 @@ function GenerateLogarithmicArithmeticOperators([string]$quantityName, [string]$ #if !WINDOWS_UWP public static $quantityName operator -($quantityName right) { - return new $quantityName(-right.$baseUnitFieldName); + return new $quantityName(-right.Value, right.Unit); } public static $quantityName operator +($quantityName left, $quantityName right) { // Logarithmic addition // Formula: $x*log10(10^(x/$x) + 10^(y/$x)) - return new $quantityName($x*Math.Log10(Math.Pow(10, left.$baseUnitFieldName/$x) + Math.Pow(10, right.$baseUnitFieldName/$x))); + return new $quantityName($x*Math.Log10(Math.Pow(10, left.Value/$x) + Math.Pow(10, right.AsBaseNumericType(left.Unit)/$x)), left.Unit); } public static $quantityName operator -($quantityName left, $quantityName right) { // Logarithmic subtraction // Formula: $x*log10(10^(x/$x) - 10^(y/$x)) - return new $quantityName($x*Math.Log10(Math.Pow(10, left.$baseUnitFieldName/$x) - Math.Pow(10, right.$baseUnitFieldName/$x))); + return new $quantityName($x*Math.Log10(Math.Pow(10, left.Value/$x) - Math.Pow(10, right.AsBaseNumericType(left.Unit)/$x)), left.Unit); } public static $quantityName operator *($baseType left, $quantityName right) { // Logarithmic multiplication = addition - return new $quantityName(left + right.$baseUnitFieldName); + return new $quantityName(left + right.Value, right.Unit); } public static $quantityName operator *($quantityName left, double right) { // Logarithmic multiplication = addition - return new $quantityName(left.$baseUnitFieldName + ($baseType)right); + return new $quantityName(left.Value + ($baseType)right, left.Unit); } public static $quantityName operator /($quantityName left, double right) { // Logarithmic division = subtraction - return new $quantityName(left.$baseUnitFieldName - ($baseType)right); + return new $quantityName(left.Value - ($baseType)right, left.Unit); } public static double operator /($quantityName left, $quantityName right) { // Logarithmic division = subtraction - return Convert.ToDouble(left.$baseUnitFieldName - right.$baseUnitFieldName); + return Convert.ToDouble(left.Value - right.AsBaseNumericType(left.Unit)); } #endif diff --git a/UnitsNet/Scripts/Include-GenerateQuantitySourceCode.ps1 b/UnitsNet/Scripts/Include-GenerateQuantitySourceCode.ps1 index bc90159613..91ceb71eed 100644 --- a/UnitsNet/Scripts/Include-GenerateQuantitySourceCode.ps1 +++ b/UnitsNet/Scripts/Include-GenerateQuantitySourceCode.ps1 @@ -1,4 +1,4 @@ -function GenerateQuantitySourceCode($quantity) +function GenerateQuantitySourceCode($quantity) { $quantityName = $quantity.Name; $units = $quantity.Units; @@ -8,30 +8,25 @@ function GenerateQuantitySourceCode($quantity) $baseUnitPluralName = $baseUnit.PluralName $baseUnitPluralNameLower = $baseUnitPluralName.ToLowerInvariant() $unitEnumName = "$quantityName" + "Unit" - $baseUnitFieldName = "_"+[Char]::ToLowerInvariant($baseUnitPluralName[0]) + $baseUnitPluralName.Substring(1) - switch ($baseType) { - long { - $convertToBaseType = "Convert.ToInt64" - break - } - double { - $convertToBaseType = "Convert.ToDouble" - break - } - decimal { - $convertToBaseType = "Convert.ToDecimal" - break - } - default { - throw "Base type not supported: $baseType" - } + $convertToBaseType = switch ($baseType) { + "long" { "Convert.ToInt64"; break } + "double" { "Convert.ToDouble"; break } + "decimal" { "Convert.ToDecimal"; break } + default { throw "Base type not supported: $baseType" } } - $obsoleteEqualityIfDouble = '' - if ($quantity.BaseType -eq "double") { - $obsoleteEqualityIfDouble = '[Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")]' + "`n " - } + $quantityValueType = switch ($baseType) { + "long" { "QuantityValue"; break } + "double" { "QuantityValue"; break } + "decimal" { "QuantityValue"; break } + default { throw "Base type not supported: $baseType" } + } + + $obsoleteEqualityIfDouble = '' + if ($quantity.BaseType -eq "double") { + $obsoleteEqualityIfDouble = '[Obsolete("It is not safe to compare equality due to using System.Double as the internal representation. It is very easy to get slightly different values due to floating point operations. Instead use Equals(other, maxError) to provide the max allowed error.")]' + "`n " + } @" //------------------------------------------------------------------------------ @@ -80,13 +75,6 @@ using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; -// Windows Runtime Component does not support CultureInfo type, so use culture name string instead for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx -#if WINDOWS_UWP -using Culture = System.String; -#else -using Culture = System.IFormatProvider; -#endif - // ReSharper disable once CheckNamespace namespace UnitsNet @@ -106,44 +94,88 @@ namespace UnitsNet #endif { /// - /// Base unit of $quantityName. + /// The numeric value this quantity was constructed with. + /// + private readonly $baseType _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly $($unitEnumName)? _unit; + + /// + /// The numeric value this quantity was constructed with. /// - private readonly $baseType $baseUnitFieldName; +#if WINDOWS_UWP + public double Value => Convert.ToDouble(_value); +#else + public $baseType Value => _value; +#endif + + /// + /// The unit this quantity was constructed with -or- if default ctor was used. + /// + public $unitEnumName Unit => _unit.GetValueOrDefault(BaseUnit); // Windows Runtime Component requires a default constructor #if WINDOWS_UWP - public $quantityName() : this(0) + public $quantityName() { + _value = 0; + _unit = BaseUnit; } #endif + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public $quantityName(double $baseUnitPluralNameLower) { - $baseUnitFieldName = $convertToBaseType($baseUnitPluralNameLower); + _value = $convertToBaseType($baseUnitPluralNameLower); + _unit = BaseUnit; } + /// + /// Creates the quantity with the given numeric value and unit. + /// + /// Numeric value. + /// Unit representation. + /// Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component. +#if WINDOWS_UWP + private +#else + public +#endif + $quantityName($baseType numericValue, $unitEnumName unit) + { + _value = numericValue; + _unit = unit; + } + // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods + /// + /// Creates the quantity with the given value assuming the base unit $baseUnitSingularName. + /// + /// Value assuming base unit $baseUnitSingularName. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - $quantityName(long $baseUnitPluralNameLower) - { - $baseUnitFieldName = $convertToBaseType($baseUnitPluralNameLower); - } + $quantityName(long $baseUnitPluralNameLower) : this($convertToBaseType($baseUnitPluralNameLower), BaseUnit) { } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods // Windows Runtime Component does not support decimal type + /// + /// Creates the quantity with the given value assuming the base unit $baseUnitSingularName. + /// + /// Value assuming base unit $baseUnitSingularName. #if WINDOWS_UWP private #else + [Obsolete("Use the constructor that takes a unit parameter. This constructor will be removed in a future version.")] public #endif - $quantityName(decimal $baseUnitPluralNameLower) - { - $baseUnitFieldName = $convertToBaseType($baseUnitPluralNameLower); - } + $quantityName(decimal $baseUnitPluralNameLower) : this($convertToBaseType($baseUnitPluralNameLower), BaseUnit) { } #region Properties @@ -155,75 +187,58 @@ namespace UnitsNet /// /// The base unit representation of this quantity for the numeric value stored internally. All conversions go via this value. /// - public static $unitEnumName BaseUnit - { - get { return $unitEnumName.$baseUnitSingularName; } - } + public static $unitEnumName BaseUnit => $unitEnumName.$baseUnitSingularName; /// /// All units of measurement for the $quantityName quantity. /// public static $unitEnumName[] Units { get; } = Enum.GetValues(typeof($unitEnumName)).Cast<$unitEnumName>().ToArray(); -"@; foreach ($unit in $units) { +"@; + foreach ($unit in $units) { $propertyName = $unit.PluralName; $obsoleteAttribute = GetObsoleteAttribute($unit); if ($obsoleteAttribute) { $obsoleteAttribute = "`r`n " + $obsoleteAttribute; # apply padding to conformance with code format in this page } - - $fromBaseToUnitFunc = $unit.FromBaseToUnitFunc.Replace("x", $baseUnitFieldName);@" - +@" /// /// Get $quantityName in $propertyName. /// $($obsoleteAttribute) - public double $propertyName - { - get { return $fromBaseToUnitFunc; } - } + public double $propertyName => As($unitEnumName.$($unit.SingularName)); "@; }@" #endregion #region Static - public static $quantityName Zero - { - get { return new $quantityName(); } - } + public static $quantityName Zero => new $quantityName(0, BaseUnit); "@; foreach ($unit in $units) { - $valueParamName = $unit.PluralName.ToLowerInvariant(); - $func = $unit.FromUnitToBaseFunc.Replace("x", "value"); - $decimalFunc = $unit.FromUnitToBaseFunc.Replace("x","Convert.ToDouble(" + $valueParamName + ")"); @" + $valueParamName = $unit.PluralName.ToLowerInvariant();@" /// /// Get $quantityName from $($unit.PluralName). /// #if WINDOWS_UWP [Windows.Foundation.Metadata.DefaultOverload] public static $quantityName From$($unit.PluralName)(double $valueParamName) - { - double value = (double) $valueParamName; - return new $quantityName($func); - } #else - public static $quantityName From$($unit.PluralName)(QuantityValue $valueParamName) + public static $quantityName From$($unit.PluralName)($quantityValueType $valueParamName) +#endif { - double value = (double) $valueParamName; - return new $quantityName(($func)); + $baseType value = ($baseType) $valueParamName; + return new $quantityName(value, $unitEnumName.$($unit.SingularName)); } -#endif "@; }@" // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP "@; foreach ($unit in $units) { - $valueParamName = $unit.PluralName.ToLowerInvariant(); - $func = $unit.FromUnitToBaseFunc.Replace("x", "$($valueParamName).Value");@" + $valueParamName = $unit.PluralName.ToLowerInvariant();@" /// /// Get nullable $quantityName from nullable $($unit.PluralName). /// - public static $($quantityName)? From$($unit.PluralName)(QuantityValue? $valueParamName) + public static $($quantityName)? From$($unit.PluralName)($($quantityValueType)? $valueParamName) { if ($($valueParamName).HasValue) { @@ -249,19 +264,10 @@ namespace UnitsNet [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] public static $quantityName From(double value, $unitEnumName fromUnit) #else - public static $quantityName From(QuantityValue value, $unitEnumName fromUnit) + public static $quantityName From($quantityValueType value, $unitEnumName fromUnit) #endif { - switch (fromUnit) - { -"@; foreach ($unit in $units) {@" - case $unitEnumName.$($unit.SingularName): - return From$($unit.PluralName)(value); -"@; }@" - - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new $quantityName(($baseType)value, fromUnit); } // Windows Runtime Component does not support nullable types (double?): https://msdn.microsoft.com/en-us/library/br230301.aspx @@ -272,22 +278,14 @@ namespace UnitsNet /// Value to convert from. /// Unit to convert from. /// $quantityName unit value. - public static $($quantityName)? From(QuantityValue? value, $unitEnumName fromUnit) + public static $($quantityName)? From($($quantityValueType)? value, $unitEnumName fromUnit) { if (!value.HasValue) { return null; } - switch (fromUnit) - { -"@; foreach ($unit in $units) {@" - case $unitEnumName.$($unit.SingularName): - return From$($unit.PluralName)(value.Value); -"@; }@" - default: - throw new NotImplementedException("fromUnit: " + fromUnit); - } + return new $quantityName(($baseType)value.Value, fromUnit); } #endif @@ -306,12 +304,29 @@ namespace UnitsNet /// Get unit abbreviation string. /// /// Unit to get abbreviation for. - /// Culture to use for localization. Defaults to Thread.CurrentUICulture. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization. Defaults to 's default culture. +#else + /// Format to use for localization. Defaults to . +#endif /// Unit abbreviation string. [UsedImplicitly] - public static string GetAbbreviation($unitEnumName unit, [CanBeNull] Culture culture) + public static string GetAbbreviation( + $unitEnumName unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit); +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif + + return UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit); } #endregion @@ -327,37 +342,37 @@ namespace UnitsNet #if !WINDOWS_UWP public static $quantityName operator -($quantityName right) { - return new $quantityName(-right.$baseUnitFieldName); + return new $quantityName(-right.Value, right.Unit); } public static $quantityName operator +($quantityName left, $quantityName right) { - return new $quantityName(left.$baseUnitFieldName + right.$baseUnitFieldName); + return new $quantityName(left.Value + right.AsBaseNumericType(left.Unit), left.Unit); } public static $quantityName operator -($quantityName left, $quantityName right) { - return new $quantityName(left.$baseUnitFieldName - right.$baseUnitFieldName); + return new $quantityName(left.Value - right.AsBaseNumericType(left.Unit), left.Unit); } public static $quantityName operator *($baseType left, $quantityName right) { - return new $quantityName(left*right.$baseUnitFieldName); + return new $quantityName(left * right.Value, right.Unit); } - public static $quantityName operator *($quantityName left, double right) + public static $quantityName operator *($quantityName left, $baseType right) { - return new $quantityName(left.$baseUnitFieldName*($baseType)right); + return new $quantityName(left.Value * right, left.Unit); } - public static $quantityName operator /($quantityName left, double right) + public static $quantityName operator /($quantityName left, $baseType right) { - return new $quantityName(left.$baseUnitFieldName/($baseType)right); + return new $quantityName(left.Value / right, left.Unit); } public static double operator /($quantityName left, $quantityName right) { - return Convert.ToDouble(left.$baseUnitFieldName/right.$baseUnitFieldName); + return left.$baseUnitPluralName / right.$baseUnitPluralName; } #endif @@ -381,41 +396,41 @@ namespace UnitsNet #endif int CompareTo($quantityName other) { - return $baseUnitFieldName.CompareTo(other.$baseUnitFieldName); + return AsBaseUnit$baseUnitPluralName().CompareTo(other.AsBaseUnit$baseUnitPluralName()); } // Windows Runtime Component does not allow operator overloads: https://msdn.microsoft.com/en-us/library/br230301.aspx #if !WINDOWS_UWP public static bool operator <=($quantityName left, $quantityName right) { - return left.$baseUnitFieldName <= right.$baseUnitFieldName; + return left.Value <= right.AsBaseNumericType(left.Unit); } public static bool operator >=($quantityName left, $quantityName right) { - return left.$baseUnitFieldName >= right.$baseUnitFieldName; + return left.Value >= right.AsBaseNumericType(left.Unit); } public static bool operator <($quantityName left, $quantityName right) { - return left.$baseUnitFieldName < right.$baseUnitFieldName; + return left.Value < right.AsBaseNumericType(left.Unit); } public static bool operator >($quantityName left, $quantityName right) { - return left.$baseUnitFieldName > right.$baseUnitFieldName; + return left.Value > right.AsBaseNumericType(left.Unit); } $($obsoleteEqualityIfDouble)public static bool operator ==($quantityName left, $quantityName right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.$baseUnitFieldName == right.$baseUnitFieldName; + return left.Value == right.AsBaseNumericType(left.Unit); } $($obsoleteEqualityIfDouble)public static bool operator !=($quantityName left, $quantityName right) { // ReSharper disable once CompareOfFloatsByEqualityOperator - return left.$baseUnitFieldName != right.$baseUnitFieldName; + return left.Value != right.AsBaseNumericType(left.Unit); } #endif @@ -426,7 +441,7 @@ namespace UnitsNet return false; } - return $baseUnitFieldName.Equals((($quantityName) obj).$baseUnitFieldName); + return AsBaseUnit$baseUnitPluralName().Equals((($quantityName) obj).AsBaseUnit$baseUnitPluralName()); } /// @@ -439,12 +454,12 @@ namespace UnitsNet /// True if the difference between the two values is not greater than the specified max. public bool Equals($quantityName other, $quantityName maxError) { - return Math.Abs($baseUnitFieldName - other.$baseUnitFieldName) <= maxError.$baseUnitFieldName; + return Math.Abs(AsBaseUnit$baseUnitPluralName() - other.AsBaseUnit$baseUnitPluralName()) <= maxError.AsBaseUnit$baseUnitPluralName(); } public override int GetHashCode() { - return $baseUnitFieldName.GetHashCode(); + return new { Value, Unit }.GetHashCode(); } #endregion @@ -454,15 +469,21 @@ namespace UnitsNet /// /// Convert to the unit representation . /// - /// Value in new unit if successful, exception otherwise. - /// If conversion was not successful. + /// Value converted to the specified unit. public double As($unitEnumName unit) { + if (Unit == unit) + { + return (double)Value; + } + + $baseType baseUnitValue = AsBaseUnit$($baseUnitPluralName)(); + switch (unit) { -"@; foreach ($unit in $units) {@" - case $unitEnumName.$($unit.SingularName): - return $($unit.PluralName); +"@; foreach ($unit in $units) { + $func = $unit.FromBaseToUnitFunc.Replace("x", "baseUnitValue");@" + case $unitEnumName.$($unit.SingularName): return $func; "@; }@" default: @@ -505,7 +526,11 @@ namespace UnitsNet /// Parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// @@ -524,17 +549,24 @@ namespace UnitsNet /// We wrap exceptions in to allow you to distinguish /// Units.NET exceptions from other exceptions. /// - public static $quantityName Parse(string str, [CanBeNull] Culture culture) + public static $quantityName Parse( + string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { if (str == null) throw new ArgumentNullException("str"); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif - return QuantityParser.Parse<$quantityName, $unitEnumName>(str, formatProvider, + + return QuantityParser.Parse<$quantityName, $unitEnumName>(str, provider, delegate(string value, string unit, IFormatProvider formatProvider2) { double parsedValue = double.Parse(value, formatProvider2); @@ -560,16 +592,41 @@ namespace UnitsNet /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. If it is null, it defaults to for parsing the number and for parsing the unit abbreviation by culture/language. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. +#else + /// Format to use when parsing number and unit. Defaults to . +#endif /// Resulting unit quantity if successful. /// /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// - public static bool TryParse([CanBeNull] string str, [CanBeNull] Culture culture, out $quantityName result) + public static bool TryParse( + [CanBeNull] string str, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + out $quantityName result) { +#if WINDOWS_UWP + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); +#else + provider = provider ?? UnitSystem.DefaultCulture; +#endif try { - result = Parse(str, culture); + + result = Parse( + str, +#if WINDOWS_UWP + cultureName); +#else + provider); +#endif + return true; } catch @@ -582,6 +639,7 @@ namespace UnitsNet /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -595,11 +653,14 @@ namespace UnitsNet /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to 's default culture. /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// /// The value of 'str' cannot be null. /// Error parsing string. + [Obsolete("Use overload that takes IFormatProvider instead of culture name. This method was only added to support WindowsRuntimeComponent and will be removed from other .NET targets.")] public static $unitEnumName ParseUnit(string str, [CanBeNull] string cultureName) { return ParseUnit(str, cultureName == null ? null : new CultureInfo(cultureName)); @@ -608,6 +669,8 @@ namespace UnitsNet /// /// Parse a unit string. /// + /// String to parse. Typically in the form: {number} {unit} + /// Format to use when parsing number and unit. Defaults to . /// /// Length.ParseUnit("m", new CultureInfo("en-US")); /// @@ -620,18 +683,18 @@ namespace UnitsNet #else public #endif - static $unitEnumName ParseUnit(string str, IFormatProvider formatProvider = null) + static $unitEnumName ParseUnit(string str, IFormatProvider provider = null) { if (str == null) throw new ArgumentNullException("str"); - var unitSystem = UnitSystem.GetCached(formatProvider); + var unitSystem = UnitSystem.GetCached(provider); var unit = unitSystem.Parse<$unitEnumName>(str.Trim()); if (unit == $unitEnumName.Undefined) { var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized $unitEnumName."); newEx.Data["input"] = str; - newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)"; + newEx.Data["provider"] = provider?.ToString() ?? "(null)"; throw newEx; } @@ -640,6 +703,7 @@ namespace UnitsNet #endregion + [Obsolete("This is no longer used since we will instead use the quantity's Unit value as default.")] /// /// Set the default unit used by ToString(). Default is $baseUnitSingularName /// @@ -651,7 +715,7 @@ namespace UnitsNet /// String representation. public override string ToString() { - return ToString(ToStringDefaultUnit); + return ToString(Unit); } /// @@ -668,76 +732,134 @@ namespace UnitsNet /// Get string representation of value and unit. Using two significant digits after radix. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// String representation. - public string ToString($unitEnumName unit, [CanBeNull] Culture culture) + public string ToString( + $unitEnumName unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName) +#else + [CanBeNull] IFormatProvider provider) +#endif { - return ToString(unit, culture, 2); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + 2); } /// /// Get string representation of value and unit. /// /// Unit representation to use. - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// The number of significant digits after the radix point. /// String representation. [UsedImplicitly] - public string ToString($unitEnumName unit, [CanBeNull] Culture culture, int significantDigitsAfterRadix) + public string ToString( + $unitEnumName unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + int significantDigitsAfterRadix) { double value = As(unit); string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); - return ToString(unit, culture, format); + return ToString( + unit, +#if WINDOWS_UWP + cultureName, +#else + provider, +#endif + format); } /// /// Get string representation of value and unit. /// - /// Culture to use for localization and number formatting. +#if WINDOWS_UWP + /// Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to 's default culture. +#else + /// Format to use for localization and number formatting. Defaults to . +#endif /// Unit representation to use. /// String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively." /// Arguments for string format. Value and unit are implictly included as arguments 0 and 1. /// String representation. [UsedImplicitly] - public string ToString($unitEnumName unit, [CanBeNull] Culture culture, [NotNull] string format, + public string ToString( + $unitEnumName unit, +#if WINDOWS_UWP + [CanBeNull] string cultureName, +#else + [CanBeNull] IFormatProvider provider, +#endif + [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); - // Windows Runtime Component does not support CultureInfo type, so use culture name string for public methods instead: https://msdn.microsoft.com/en-us/library/br230301.aspx #if WINDOWS_UWP - IFormatProvider formatProvider = culture == null ? null : new CultureInfo(culture); + // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx + IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName); #else - IFormatProvider formatProvider = culture; + provider = provider ?? UnitSystem.DefaultCulture; #endif + double value = As(unit); - object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, formatProvider, args); - return string.Format(formatProvider, format, formatArgs); + object[] formatArgs = UnitFormatter.GetFormatArgs(unit, value, provider, args); + return string.Format(provider, format, formatArgs); } /// /// Represents the largest possible value of $quantityName /// - public static $quantityName MaxValue - { - get - { - return new $quantityName($baseType.MaxValue); - } - } + public static $quantityName MaxValue => new $quantityName($baseType.MaxValue, BaseUnit); /// /// Represents the smallest possible value of $quantityName /// - public static $quantityName MinValue + public static $quantityName MinValue => new $quantityName($baseType.MinValue, BaseUnit); + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private $baseType AsBaseUnit$baseUnitPluralName() { - get + if (Unit == $unitEnumName.$baseUnitSingularName) { return _value; } + + switch (Unit) { - return new $quantityName($baseType.MinValue); - } - } - } +"@; foreach ($unit in $units) { + $func = $unit.FromUnitToBaseFunc.Replace("x", "_value");@" + case $unitEnumName.$($unit.SingularName): return $func; +"@; }@" + default: + throw new NotImplementedException("Unit not implemented: " + Unit); + } + } + + /// Convenience method for working with internal numeric type. + private $baseType AsBaseNumericType($unitEnumName unit) => $convertToBaseType(As(unit)); + } } "@; -} \ No newline at end of file +} diff --git a/UnitsNet/UnitsNet.NetStandard10.Signed.csproj b/UnitsNet/UnitsNet.NetStandard10.Signed.csproj index ec8f59da3b..dd4c51e7c7 100644 --- a/UnitsNet/UnitsNet.NetStandard10.Signed.csproj +++ b/UnitsNet/UnitsNet.NetStandard10.Signed.csproj @@ -9,6 +9,7 @@ + SIGNED true $(MSBuildProjectDirectory)\..\UnitsNet.snk