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