From d805333c45dbeae28cd7867bcd7f9fe910f3a981 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 4 Dec 2019 13:38:53 -0600 Subject: [PATCH 01/24] From YektaMirkan/Units - Added reference pressure property - by gratestas --- UnitsNet.Tests/CustomCode/PressureTests.cs | 9 +++++++++ UnitsNet/GeneratedCode/Quantities/Pressure.g.cs | 5 +++++ 2 files changed, 14 insertions(+) diff --git a/UnitsNet.Tests/CustomCode/PressureTests.cs b/UnitsNet.Tests/CustomCode/PressureTests.cs index 645501b341..e62868879c 100644 --- a/UnitsNet.Tests/CustomCode/PressureTests.cs +++ b/UnitsNet.Tests/CustomCode/PressureTests.cs @@ -1,6 +1,7 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using UnitsNet.Units; using Xunit; namespace UnitsNet.Tests.CustomCode @@ -90,6 +91,14 @@ public class PressureTests : PressureTestsBase protected override double MillipascalsInOnePascal => 1e3; + [Fact] + public void ReferencePressure() + { + var referencePressure = Pressure.Reference; + Pressure.Reference = new Pressure(2, PressureUnit.Atmosphere); + Assert.False(referencePressure.Atmospheres.Equals(Pressure.Reference.Atmospheres)); + Assert.True(Pressure.Reference.Atmospheres.Equals(2)); + } [Fact] public void AreaTimesPressureEqualsForce() { diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs index 2b23dacf30..b273a565b0 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs @@ -155,6 +155,11 @@ public Pressure(double value, UnitSystem unitSystem) /// public static Pressure MinValue { get; } = new Pressure(double.MinValue, BaseUnit); + /// + /// Represents the pressure at which Pressure is referenced (1 atm) + /// + public static Pressure Reference { get; set; } = new Pressure(1, PressureUnit.Atmosphere); + /// /// The of this quantity. /// From b8c6393c575f93e1759e0fe4c38a83ca6fbfa238 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 4 Dec 2019 13:52:35 -0600 Subject: [PATCH 02/24] From YektaMirkan/Units - Added enum of pressure reference - by gratestas --- UnitsNet/GeneratedCode/Units/PressureUnit.g.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs b/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs index 3c4a239081..bbe7fb62a1 100644 --- a/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs @@ -69,6 +69,12 @@ public enum PressureUnit TonneForcePerSquareMillimeter, Torr, } - - #pragma warning restore 1591 + enum PressureReference + { + Undefined = 0, + Absolute, + Gauge, + Vacuum, + } +#pragma warning restore 1591 } From b327ad5810ae6811199574db40e5bf09b986ab54 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 4 Dec 2019 16:30:51 -0600 Subject: [PATCH 03/24] From YektaMirkan/Units - Added pressure wrapper for pressure reference conversion - by gratestas --- .axoCover/settings.json | 19 +++ .../GeneratedCode/PressureTestsBase.g.cs | 55 ++++++++ .../CustomCode/Wrappers/Pressure.Wrapper.cs | 125 ++++++++++++++++++ .../GeneratedCode/Quantities/Pressure.g.cs | 2 +- .../GeneratedCode/Units/PressureUnit.g.cs | 2 +- UnitsNet/UnitsNet.csproj | 4 +- 6 files changed, 203 insertions(+), 4 deletions(-) create mode 100644 .axoCover/settings.json create mode 100644 UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs diff --git a/.axoCover/settings.json b/.axoCover/settings.json new file mode 100644 index 0000000000..5f4b671000 --- /dev/null +++ b/.axoCover/settings.json @@ -0,0 +1,19 @@ +{ + "TestRunner": "", + "TestPlatform": "x86", + "TestApartmentState": "STA", + "TestAdapterMode": "Standard", + "IsRedirectingFrameworkAssemblies": true, + "TestSettings": "", + "ExcludeAttributes": "System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute", + "ExcludeFiles": "", + "ExcludeDirectories": "", + "Filters": "+[*]*", + "IsIncludingSolutionAssemblies": true, + "IsExcludingTestAssemblies": false, + "IsCoveringByTest": true, + "IsMergingByHash": true, + "IsSkippingAutoProps": true, + "IsVisitorCountLimited": false, + "VisitorCountLimit": 10 +} \ No newline at end of file diff --git a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs index 0306563dd9..6aa592d201 100644 --- a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs @@ -20,6 +20,7 @@ using System; using System.Linq; using UnitsNet.Units; +using UnitsNet.CustomCode.Wrappers; using Xunit; // Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? @@ -649,5 +650,59 @@ public void BaseDimensionsShouldNeverBeNull() { Assert.False(Pressure.BaseDimensions is null); } + + // Pressure Measurement References + + [Fact] + public void ReferenceConversion_WithDefaultReferencedPressure() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + + AssertEx.EqualTolerance(2, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + AssertEx.EqualTolerance(2, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + + refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); + + AssertEx.EqualTolerance(4, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + AssertEx.EqualTolerance(3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + AssertEx.EqualTolerance(3, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + + refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); + + AssertEx.EqualTolerance(3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + AssertEx.EqualTolerance(3, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + AssertEx.EqualTolerance(2, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + } + + [Fact] + public void ReferenceConversion_WithSetReferencedPressure() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + + AssertEx.EqualTolerance(2, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + + ReferencePressure.ReferencedPressure = new Pressure(2, PressureUnit.Atmosphere); + AssertEx.EqualTolerance(1, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + + ReferencePressure.ReferencedPressure = new Pressure(1.5, PressureUnit.Atmosphere); + AssertEx.EqualTolerance(1.5, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + } + + [Fact] + public void ReferencePressure_isChanged() + { + var referencePressure = ReferencePressure.ReferencedPressure; + ReferencePressure.ReferencedPressure = new Pressure(2, PressureUnit.Atmosphere); + + Assert.False(referencePressure.Atmospheres.Equals(ReferencePressure.ReferencedPressure.Atmospheres)); + Assert.True(ReferencePressure.ReferencedPressure.Atmospheres.Equals(2)); + } + + [Fact] + public void ReferencesDoesNotContainUndefined() + { + Assert.DoesNotContain(PressureReference.Undefined, ReferencePressure.References); + } } } diff --git a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs new file mode 100644 index 0000000000..28c8659e84 --- /dev/null +++ b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnitsNet.Units; + +namespace UnitsNet.CustomCode.Wrappers +{ + /// + /// From gratestas in #422 + /// Pressure is a state function, for its measurement depends on environmental factors such as ambient pressure, elevation above sea level and local weather conditions. For two persons located in the different environment to speak of the same pressure, one must relate it to a reference. There are three basis reference: absolute, gauge, vacuum + /// Absolute is zero-referenced to the total vacuum. + /// Gauge refers to a level of the local atmospheric pressure. + /// Vacuum is the negative of the gauge. + ///Therefore, to obtain consistent and qualitative data, the reference measurement is crucial. + /// + public struct ReferencePressure + { + /// + /// + /// + /// + /// + public ReferencePressure(Pressure pressure, PressureReference reference) + { + _reference = reference; + Pressure = pressure; + } + + /// + /// ctor using BaseReference of absolute to assign default _reference + /// + /// + public ReferencePressure(Pressure pressure) + { + _reference = BaseReference; + Pressure = pressure; + } + + /// + /// The public repersentation of the measured reference this quantity was constructed with. + /// + public PressureReference Reference => _reference.GetValueOrDefault(BaseReference); + + /// + /// The measured reference this quantity was constructed with. + /// + private readonly PressureReference? _reference; + + /// + /// List property of reference options: Gauge, Absolute, and Vacuum + /// + public static List References { get; } = Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] { PressureReference.Undefined }).ToList(); + + /// + /// The base reference representation of this quantity for the numeric value stored internally. All conversions go via this value. + /// + public static PressureReference BaseReference { get; } = PressureReference.Absolute; + + private Pressure Pressure { get; } + + /// + /// Get Gauge Pressure. + /// It refers pressure level above Reference Pressure. + /// + public Pressure Gauge => As(PressureReference.Gauge); + + /// + /// Get Absolute Pressure. + /// It is zero-referenced pressure to the perfect vacuum. + /// + public Pressure Absolute => As(PressureReference.Absolute); + + /// + /// Get Vacuum Pressure. + /// It is a negative Gauge Pressure when Absolute Pressure is below Reference Pressure. + /// + public Pressure Vacuum => As(PressureReference.Vacuum); + + + private Pressure As(PressureReference reference) + { + if (Reference == reference) + return new Pressure(Pressure.Value, Pressure.Unit); + + var converted = AsBaseNumericType(reference); + + if (converted < 0) converted *= -1; + return new Pressure(converted, Pressure.Unit); + } + + private double AsBaseNumericType(PressureReference reference) + { + if (Reference == reference) + return Pressure.Value; + + var baseReferenceValue = AsBaseReference(); + var negatingValue = Reference == PressureReference.Vacuum ? -1 : 1; + + switch (reference) + { + case PressureReference.Absolute: return baseReferenceValue; + case PressureReference.Gauge: return baseReferenceValue - ReferencedPressure.ToUnit(Pressure.Unit).Value; + case PressureReference.Vacuum: return ReferencedPressure.ToUnit(Pressure.Unit).Value - negatingValue * baseReferenceValue; + default: + throw new NotImplementedException($"Can not convert {Reference} to {reference}."); + } + } + + private double AsBaseReference() + { + switch (Reference) + { + case PressureReference.Absolute: return Pressure.Value; + case PressureReference.Gauge: return ReferencedPressure.ToUnit(Pressure.Unit).Value + Pressure.Value; + case PressureReference.Vacuum: return ReferencedPressure.ToUnit(Pressure.Unit).Value - Pressure.Value; + default: + throw new NotImplementedException($"Can not convert {Reference} to base reference."); + } + } + /// + /// Represents the pressure at which Pressure is referenced (1 atm default) + /// + public static Pressure ReferencedPressure { get; set; } = new Pressure(1, PressureUnit.Atmosphere); + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs index b273a565b0..0936ad33f0 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs @@ -156,7 +156,7 @@ public Pressure(double value, UnitSystem unitSystem) public static Pressure MinValue { get; } = new Pressure(double.MinValue, BaseUnit); /// - /// Represents the pressure at which Pressure is referenced (1 atm) + /// Represents the pressure at which Pressure is referenced (1 atm default) /// public static Pressure Reference { get; set; } = new Pressure(1, PressureUnit.Atmosphere); diff --git a/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs b/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs index bbe7fb62a1..118590e855 100644 --- a/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs @@ -69,7 +69,7 @@ public enum PressureUnit TonneForcePerSquareMillimeter, Torr, } - enum PressureReference + public enum PressureReference { Undefined = 0, Absolute, diff --git a/UnitsNet/UnitsNet.csproj b/UnitsNet/UnitsNet.csproj index 1996c4eef2..1b9cda3e26 100644 --- a/UnitsNet/UnitsNet.csproj +++ b/UnitsNet/UnitsNet.csproj @@ -1,4 +1,4 @@ - + UnitsNet @@ -39,7 +39,7 @@ true UnitsNet - + From ee072e9fcab51314e04cda32f3d247d2e235604f Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 4 Dec 2019 16:37:29 -0600 Subject: [PATCH 04/24] Broke out tests into individual assertions. Corrected test values in assertions. --- .../GeneratedCode/PressureTestsBase.g.cs | 77 +++++++++++-------- 1 file changed, 45 insertions(+), 32 deletions(-) diff --git a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs index 6aa592d201..3291905ad2 100644 --- a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs @@ -652,53 +652,66 @@ public void BaseDimensionsShouldNeverBeNull() } // Pressure Measurement References - [Fact] - public void ReferenceConversion_WithDefaultReferencedPressure() + public void ReferenceConversion_WithDefaultPressureReference_PressureReferenceIsAbsolute() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + AssertEx.Equals(PressureReference.Absolute, refPressure.Reference); + } + [Fact] + public void ReferenceConversion_WithDefaultPressureReference_GaugeIsOneLess() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); - AssertEx.EqualTolerance(2, refPressure.Gauge.Atmospheres, AtmospheresTolerance); - AssertEx.EqualTolerance(2, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithDefaultPressureReference_VacuumIsNegativeGaugeAsOneLess() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + AssertEx.EqualTolerance(-2, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithDefaultPressureReference_AbsoluteIsEqual() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); - - refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); - + } + [Fact] + public void ReferenceConversion_WithGaugePressureReference_AbsoluteIsOneMore() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); AssertEx.EqualTolerance(4, refPressure.Absolute.Atmospheres, AtmospheresTolerance); - AssertEx.EqualTolerance(3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithGaugePressureReference_VacuumIsNegativeGauge() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); + AssertEx.EqualTolerance(-3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithGaugePressureReference_GaugeIsEqual() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); AssertEx.EqualTolerance(3, refPressure.Gauge.Atmospheres, AtmospheresTolerance); - - refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); - + } + [Fact] + public void ReferenceConversion_WithVacuumPressureReference_VacuumIsEqual() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); AssertEx.EqualTolerance(3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); - AssertEx.EqualTolerance(3, refPressure.Gauge.Atmospheres, AtmospheresTolerance); - AssertEx.EqualTolerance(2, refPressure.Absolute.Atmospheres, AtmospheresTolerance); } - [Fact] - public void ReferenceConversion_WithSetReferencedPressure() + public void ReferenceConversion_WithVacuumPressureReference_GaugeIsNegativeVacuum() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); - - AssertEx.EqualTolerance(2, refPressure.Gauge.Atmospheres, AtmospheresTolerance); - - ReferencePressure.ReferencedPressure = new Pressure(2, PressureUnit.Atmosphere); - AssertEx.EqualTolerance(1, refPressure.Gauge.Atmospheres, AtmospheresTolerance); - - ReferencePressure.ReferencedPressure = new Pressure(1.5, PressureUnit.Atmosphere); - AssertEx.EqualTolerance(1.5, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); + AssertEx.EqualTolerance(-3, refPressure.Gauge.Atmospheres, AtmospheresTolerance); } - [Fact] - public void ReferencePressure_isChanged() + public void ReferenceConversion_WithVacuumPressureReference_AbsoluteIsOneLessNegative() { - var referencePressure = ReferencePressure.ReferencedPressure; - ReferencePressure.ReferencedPressure = new Pressure(2, PressureUnit.Atmosphere); - - Assert.False(referencePressure.Atmospheres.Equals(ReferencePressure.ReferencedPressure.Atmospheres)); - Assert.True(ReferencePressure.ReferencedPressure.Atmospheres.Equals(2)); + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); + AssertEx.EqualTolerance(-2, refPressure.Absolute.Atmospheres, AtmospheresTolerance); } - [Fact] public void ReferencesDoesNotContainUndefined() { From 27b06e3ae53c0c73d2d30d98e0cf3077adefe402 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 4 Dec 2019 16:50:23 -0600 Subject: [PATCH 05/24] Removed line in ReferencePressure.As that was causing sign errors and incorrect vaules and failed test results. --- UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs index 28c8659e84..61ce93e197 100644 --- a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs +++ b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs @@ -84,7 +84,6 @@ private Pressure As(PressureReference reference) var converted = AsBaseNumericType(reference); - if (converted < 0) converted *= -1; return new Pressure(converted, Pressure.Unit); } From c7fcabcbf1b40669f120fcdd41922fb65ff7d686 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 4 Dec 2019 18:30:48 -0600 Subject: [PATCH 06/24] Corrected issues with pressures less than absolute zero --- .../GeneratedCode/PressureTestsBase.g.cs | 16 ++++++++++++++-- UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs | 12 +++++++++--- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs index 3291905ad2..ae0aa8d798 100644 --- a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs @@ -702,15 +702,27 @@ public void ReferenceConversion_WithVacuumPressureReference_VacuumIsEqual() } [Fact] public void ReferenceConversion_WithVacuumPressureReference_GaugeIsNegativeVacuum() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); + AssertEx.EqualTolerance(-1, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithVacuumPressureReferenceToGauge_AbsoluteCannotBeLessThanZero() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); - AssertEx.EqualTolerance(-3, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + Assert.Throws(() => refPressure.Gauge.Atmospheres); } [Fact] public void ReferenceConversion_WithVacuumPressureReference_AbsoluteIsOneLessNegative() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); + AssertEx.EqualTolerance(0, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithVacuumPressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); - AssertEx.EqualTolerance(-2, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + Assert.Throws(() => refPressure.Absolute.Atmospheres ); } [Fact] public void ReferencesDoesNotContainUndefined() diff --git a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs index 61ce93e197..99a5e0b4d6 100644 --- a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs +++ b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs @@ -109,9 +109,15 @@ private double AsBaseReference() { switch (Reference) { - case PressureReference.Absolute: return Pressure.Value; - case PressureReference.Gauge: return ReferencedPressure.ToUnit(Pressure.Unit).Value + Pressure.Value; - case PressureReference.Vacuum: return ReferencedPressure.ToUnit(Pressure.Unit).Value - Pressure.Value; + case PressureReference.Absolute: + if (Pressure.Value < 0) throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); + else return Pressure.Value; + case PressureReference.Gauge: + if (Pressure.Value * -1 > ReferencedPressure.ToUnit(Pressure.Unit).Value) throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); + else return ReferencedPressure.ToUnit(Pressure.Unit).Value + Pressure.Value; + case PressureReference.Vacuum: + if (Pressure.Value > ReferencedPressure.ToUnit(Pressure.Unit).Value) throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); + else return ReferencedPressure.ToUnit(Pressure.Unit).Value - Pressure.Value; default: throw new NotImplementedException($"Can not convert {Reference} to base reference."); } From e69383fb6f61e606d9642ccf7d63d315b4534403 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Fri, 6 Dec 2019 11:15:06 -0600 Subject: [PATCH 07/24] Updated nuget packages --- CodeGen/CodeGen.csproj | 9 +++++---- UnitsNet.Benchmark/UnitsNet.Benchmark.csproj | 6 +++--- ...tsNet.Serialization.JsonNet.CompatibilityTests.csproj | 2 +- .../UnitsNet.Serialization.JsonNet.Tests.csproj | 2 +- .../UnitsNet.Serialization.JsonNet.csproj | 4 ++-- UnitsNet.Tests/UnitsNet.Tests.csproj | 2 +- UnitsNet/UnitsNet.csproj | 2 +- 7 files changed, 14 insertions(+), 13 deletions(-) diff --git a/CodeGen/CodeGen.csproj b/CodeGen/CodeGen.csproj index 57ca1e52e8..32d6752568 100644 --- a/CodeGen/CodeGen.csproj +++ b/CodeGen/CodeGen.csproj @@ -3,13 +3,14 @@ Exe netcoreapp2.1 + 7.3 - - - - + + + + diff --git a/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj b/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj index f5c9ac95c1..3d4705983b 100644 --- a/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj +++ b/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj @@ -14,9 +14,9 @@ - - - + + + all diff --git a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj index 5267b286c3..18fc41ad17 100644 --- a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj +++ b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj @@ -17,7 +17,7 @@ - + diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj index a74f41c550..29ee91f9b5 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj @@ -15,7 +15,7 @@ - + diff --git a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj index 146fb1a882..34fd947682 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj +++ b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj @@ -42,8 +42,8 @@ - - + + diff --git a/UnitsNet.Tests/UnitsNet.Tests.csproj b/UnitsNet.Tests/UnitsNet.Tests.csproj index 53df8ca761..3f4d558402 100644 --- a/UnitsNet.Tests/UnitsNet.Tests.csproj +++ b/UnitsNet.Tests/UnitsNet.Tests.csproj @@ -24,7 +24,7 @@ - + diff --git a/UnitsNet/UnitsNet.csproj b/UnitsNet/UnitsNet.csproj index 1b9cda3e26..a7659d1813 100644 --- a/UnitsNet/UnitsNet.csproj +++ b/UnitsNet/UnitsNet.csproj @@ -43,7 +43,7 @@ - + From 77137f800d356e7dbe2003cbc5fb7aa2eb797b52 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Fri, 6 Dec 2019 12:18:02 -0600 Subject: [PATCH 08/24] Improved code coverage and corrected exception handling --- .../GeneratedCode/PressureTestsBase.g.cs | 22 +++++++++++++++++-- .../CustomCode/Wrappers/Pressure.Wrapper.cs | 8 +++---- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs index ae0aa8d798..1b6c9ce37e 100644 --- a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs @@ -697,8 +697,8 @@ public void ReferenceConversion_WithGaugePressureReference_GaugeIsEqual() [Fact] public void ReferenceConversion_WithVacuumPressureReference_VacuumIsEqual() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); - AssertEx.EqualTolerance(3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); + AssertEx.EqualTolerance(1, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); } [Fact] public void ReferenceConversion_WithVacuumPressureReference_GaugeIsNegativeVacuum() @@ -725,6 +725,24 @@ public void ReferenceConversion_WithVacuumPressureReferenceToAbsolute_AbsoluteCa Assert.Throws(() => refPressure.Absolute.Atmospheres ); } [Fact] + public void ReferenceConversion_WithAbsolutePressureReferenceToAbsolute_AbsoluteIsEqual() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Absolute); + AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithNegativeAbsolutePressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Absolute); + Assert.Throws(() => refPressure.Absolute.Atmospheres); + } + [Fact] + public void ReferenceConversion_WithNegativeGaugePressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Gauge); + Assert.Throws(() => refPressure.Absolute.Atmospheres); + } + [Fact] public void ReferencesDoesNotContainUndefined() { Assert.DoesNotContain(PressureReference.Undefined, ReferencePressure.References); diff --git a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs index 99a5e0b4d6..d77ea7bb3a 100644 --- a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs +++ b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs @@ -79,9 +79,6 @@ public ReferencePressure(Pressure pressure) private Pressure As(PressureReference reference) { - if (Reference == reference) - return new Pressure(Pressure.Value, Pressure.Unit); - var converted = AsBaseNumericType(reference); return new Pressure(converted, Pressure.Unit); @@ -89,10 +86,11 @@ private Pressure As(PressureReference reference) private double AsBaseNumericType(PressureReference reference) { + var baseReferenceValue = AsBaseReference(); + if (Reference == reference) return Pressure.Value; - var baseReferenceValue = AsBaseReference(); var negatingValue = Reference == PressureReference.Vacuum ? -1 : 1; switch (reference) @@ -125,6 +123,6 @@ private double AsBaseReference() /// /// Represents the pressure at which Pressure is referenced (1 atm default) /// - public static Pressure ReferencedPressure { get; set; } = new Pressure(1, PressureUnit.Atmosphere); + public static Pressure ReferencedPressure { get; } = new Pressure(1, PressureUnit.Atmosphere); } } From 71708c84ed554b2b80dfb885ab120d23533af724 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Fri, 6 Dec 2019 12:58:07 -0600 Subject: [PATCH 09/24] Cleaned up unnecessary coverage file --- .axoCover/settings.json | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 .axoCover/settings.json diff --git a/.axoCover/settings.json b/.axoCover/settings.json deleted file mode 100644 index 5f4b671000..0000000000 --- a/.axoCover/settings.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "TestRunner": "", - "TestPlatform": "x86", - "TestApartmentState": "STA", - "TestAdapterMode": "Standard", - "IsRedirectingFrameworkAssemblies": true, - "TestSettings": "", - "ExcludeAttributes": "System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute", - "ExcludeFiles": "", - "ExcludeDirectories": "", - "Filters": "+[*]*", - "IsIncludingSolutionAssemblies": true, - "IsExcludingTestAssemblies": false, - "IsCoveringByTest": true, - "IsMergingByHash": true, - "IsSkippingAutoProps": true, - "IsVisitorCountLimited": false, - "VisitorCountLimit": 10 -} \ No newline at end of file From b9d50453cb3fa4e5c2fd681978afd77dea771605 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Fri, 6 Dec 2019 13:40:26 -0600 Subject: [PATCH 10/24] Relocated the code created by gratestas from GeneratedCode to CustomCode --- UnitsNet.Tests/CustomCode/PressureTests.cs | 109 ++++++++++++++++-- .../GeneratedCode/PressureTestsBase.g.cs | 97 ---------------- UnitsNet/CustomCode/Units/PressureUnit.g.cs | 34 ++++++ .../CustomCode/Wrappers/Pressure.Wrapper.cs | 1 + .../GeneratedCode/Units/PressureUnit.g.cs | 7 -- 5 files changed, 135 insertions(+), 113 deletions(-) create mode 100644 UnitsNet/CustomCode/Units/PressureUnit.g.cs diff --git a/UnitsNet.Tests/CustomCode/PressureTests.cs b/UnitsNet.Tests/CustomCode/PressureTests.cs index e62868879c..b0dc0f5c56 100644 --- a/UnitsNet.Tests/CustomCode/PressureTests.cs +++ b/UnitsNet.Tests/CustomCode/PressureTests.cs @@ -1,8 +1,10 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using UnitsNet.Units; +using UnitsNet.CustomCode.Wrappers; +using UnitsNet.CustomCode.Units; using Xunit; +using System; namespace UnitsNet.Tests.CustomCode { @@ -91,14 +93,6 @@ public class PressureTests : PressureTestsBase protected override double MillipascalsInOnePascal => 1e3; - [Fact] - public void ReferencePressure() - { - var referencePressure = Pressure.Reference; - Pressure.Reference = new Pressure(2, PressureUnit.Atmosphere); - Assert.False(referencePressure.Atmospheres.Equals(Pressure.Reference.Atmospheres)); - Assert.True(Pressure.Reference.Atmospheres.Equals(2)); - } [Fact] public void AreaTimesPressureEqualsForce() { @@ -126,5 +120,102 @@ public void PressureDividedByLengthEqualsSpecificWeight() SpecificWeight specificWeight = Pressure.FromPascals(20) / Length.FromMeters(2); Assert.Equal(SpecificWeight.FromNewtonsPerCubicMeter(10), specificWeight); } + // Pressure Measurement References + [Fact] + public void ReferenceConversion_WithDefaultPressureReference_PressureReferenceIsAbsolute() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + AssertEx.Equals(PressureReference.Absolute, refPressure.Reference); + } + [Fact] + public void ReferenceConversion_WithDefaultPressureReference_GaugeIsOneLess() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + AssertEx.EqualTolerance(2, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithDefaultPressureReference_VacuumIsNegativeGaugeAsOneLess() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + AssertEx.EqualTolerance(-2, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithDefaultPressureReference_AbsoluteIsEqual() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithGaugePressureReference_AbsoluteIsOneMore() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); + AssertEx.EqualTolerance(4, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithGaugePressureReference_VacuumIsNegativeGauge() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); + AssertEx.EqualTolerance(-3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithGaugePressureReference_GaugeIsEqual() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); + AssertEx.EqualTolerance(3, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithVacuumPressureReference_VacuumIsEqual() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); + AssertEx.EqualTolerance(1, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithVacuumPressureReference_GaugeIsNegativeVacuum() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); + AssertEx.EqualTolerance(-1, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithVacuumPressureReferenceToGauge_AbsoluteCannotBeLessThanZero() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); + Assert.Throws(() => refPressure.Gauge.Atmospheres); + } + [Fact] + public void ReferenceConversion_WithVacuumPressureReference_AbsoluteIsOneLessNegative() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); + AssertEx.EqualTolerance(0, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithVacuumPressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); + Assert.Throws(() => refPressure.Absolute.Atmospheres); + } + [Fact] + public void ReferenceConversion_WithAbsolutePressureReferenceToAbsolute_AbsoluteIsEqual() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Absolute); + AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + } + [Fact] + public void ReferenceConversion_WithNegativeAbsolutePressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Absolute); + Assert.Throws(() => refPressure.Absolute.Atmospheres); + } + [Fact] + public void ReferenceConversion_WithNegativeGaugePressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() + { + ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Gauge); + Assert.Throws(() => refPressure.Absolute.Atmospheres); + } + [Fact] + public void ReferencesDoesNotContainUndefined() + { + Assert.DoesNotContain(PressureReference.Undefined, ReferencePressure.References); + } + } } diff --git a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs index 1b6c9ce37e..0e790567d1 100644 --- a/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/PressureTestsBase.g.cs @@ -20,7 +20,6 @@ using System; using System.Linq; using UnitsNet.Units; -using UnitsNet.CustomCode.Wrappers; using Xunit; // Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? @@ -651,101 +650,5 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Pressure.BaseDimensions is null); } - // Pressure Measurement References - [Fact] - public void ReferenceConversion_WithDefaultPressureReference_PressureReferenceIsAbsolute() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); - AssertEx.Equals(PressureReference.Absolute, refPressure.Reference); - } - [Fact] - public void ReferenceConversion_WithDefaultPressureReference_GaugeIsOneLess() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); - AssertEx.EqualTolerance(2, refPressure.Gauge.Atmospheres, AtmospheresTolerance); - } - [Fact] - public void ReferenceConversion_WithDefaultPressureReference_VacuumIsNegativeGaugeAsOneLess() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); - AssertEx.EqualTolerance(-2, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); - } - [Fact] - public void ReferenceConversion_WithDefaultPressureReference_AbsoluteIsEqual() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); - AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); - } - [Fact] - public void ReferenceConversion_WithGaugePressureReference_AbsoluteIsOneMore() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); - AssertEx.EqualTolerance(4, refPressure.Absolute.Atmospheres, AtmospheresTolerance); - } - [Fact] - public void ReferenceConversion_WithGaugePressureReference_VacuumIsNegativeGauge() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); - AssertEx.EqualTolerance(-3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); - } - [Fact] - public void ReferenceConversion_WithGaugePressureReference_GaugeIsEqual() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); - AssertEx.EqualTolerance(3, refPressure.Gauge.Atmospheres, AtmospheresTolerance); - } - [Fact] - public void ReferenceConversion_WithVacuumPressureReference_VacuumIsEqual() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); - AssertEx.EqualTolerance(1, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); - } - [Fact] - public void ReferenceConversion_WithVacuumPressureReference_GaugeIsNegativeVacuum() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); - AssertEx.EqualTolerance(-1, refPressure.Gauge.Atmospheres, AtmospheresTolerance); - } - [Fact] - public void ReferenceConversion_WithVacuumPressureReferenceToGauge_AbsoluteCannotBeLessThanZero() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); - Assert.Throws(() => refPressure.Gauge.Atmospheres); - } - [Fact] - public void ReferenceConversion_WithVacuumPressureReference_AbsoluteIsOneLessNegative() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); - AssertEx.EqualTolerance(0, refPressure.Absolute.Atmospheres, AtmospheresTolerance); - } - [Fact] - public void ReferenceConversion_WithVacuumPressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); - Assert.Throws(() => refPressure.Absolute.Atmospheres ); - } - [Fact] - public void ReferenceConversion_WithAbsolutePressureReferenceToAbsolute_AbsoluteIsEqual() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Absolute); - AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); - } - [Fact] - public void ReferenceConversion_WithNegativeAbsolutePressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Absolute); - Assert.Throws(() => refPressure.Absolute.Atmospheres); - } - [Fact] - public void ReferenceConversion_WithNegativeGaugePressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Gauge); - Assert.Throws(() => refPressure.Absolute.Atmospheres); - } - [Fact] - public void ReferencesDoesNotContainUndefined() - { - Assert.DoesNotContain(PressureReference.Undefined, ReferencePressure.References); - } } } diff --git a/UnitsNet/CustomCode/Units/PressureUnit.g.cs b/UnitsNet/CustomCode/Units/PressureUnit.g.cs new file mode 100644 index 0000000000..e2d224d60d --- /dev/null +++ b/UnitsNet/CustomCode/Units/PressureUnit.g.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +// ReSharper disable once CheckNamespace +namespace UnitsNet.CustomCode.Units +{ + // Disable missing XML comment warnings for the generated unit enums. + #pragma warning disable 1591 + + public enum PressureReference + { + Undefined = 0, + Absolute, + Gauge, + Vacuum, + } +#pragma warning restore 1591 +} diff --git a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs index d77ea7bb3a..7213815e18 100644 --- a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs +++ b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using UnitsNet.Units; +using UnitsNet.CustomCode.Units; namespace UnitsNet.CustomCode.Wrappers { diff --git a/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs b/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs index 118590e855..026472aad0 100644 --- a/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs +++ b/UnitsNet/GeneratedCode/Units/PressureUnit.g.cs @@ -69,12 +69,5 @@ public enum PressureUnit TonneForcePerSquareMillimeter, Torr, } - public enum PressureReference - { - Undefined = 0, - Absolute, - Gauge, - Vacuum, - } #pragma warning restore 1591 } From db74663a318ac8d3d9f77c61ffb9152da5db0c89 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Mon, 9 Dec 2019 10:10:30 -0600 Subject: [PATCH 11/24] Old habits... rolling back NuGet packages to originals --- CodeGen/CodeGen.csproj | 8 ++++---- UnitsNet.Benchmark/UnitsNet.Benchmark.csproj | 6 +++--- ...itsNet.Serialization.JsonNet.CompatibilityTests.csproj | 2 +- .../UnitsNet.Serialization.JsonNet.Tests.csproj | 2 +- .../UnitsNet.Serialization.JsonNet.csproj | 4 ++-- UnitsNet.Tests/UnitsNet.Tests.csproj | 2 +- UnitsNet/UnitsNet.csproj | 2 +- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/CodeGen/CodeGen.csproj b/CodeGen/CodeGen.csproj index 32d6752568..04c8251645 100644 --- a/CodeGen/CodeGen.csproj +++ b/CodeGen/CodeGen.csproj @@ -7,10 +7,10 @@ - - - - + + + + diff --git a/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj b/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj index 3d4705983b..f5c9ac95c1 100644 --- a/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj +++ b/UnitsNet.Benchmark/UnitsNet.Benchmark.csproj @@ -14,9 +14,9 @@ - - - + + + all diff --git a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj index 18fc41ad17..5267b286c3 100644 --- a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj +++ b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj @@ -17,7 +17,7 @@ - + diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj index 29ee91f9b5..a74f41c550 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj @@ -15,7 +15,7 @@ - + diff --git a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj index 34fd947682..146fb1a882 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj +++ b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj @@ -42,8 +42,8 @@ - - + + diff --git a/UnitsNet.Tests/UnitsNet.Tests.csproj b/UnitsNet.Tests/UnitsNet.Tests.csproj index 3f4d558402..53df8ca761 100644 --- a/UnitsNet.Tests/UnitsNet.Tests.csproj +++ b/UnitsNet.Tests/UnitsNet.Tests.csproj @@ -24,7 +24,7 @@ - + diff --git a/UnitsNet/UnitsNet.csproj b/UnitsNet/UnitsNet.csproj index a7659d1813..1b9cda3e26 100644 --- a/UnitsNet/UnitsNet.csproj +++ b/UnitsNet/UnitsNet.csproj @@ -43,7 +43,7 @@ - + From 82d65db435784bb280348365832f1c61bde0c40f Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Mon, 9 Dec 2019 10:27:31 -0600 Subject: [PATCH 12/24] Renamed unit tests --- UnitsNet.Tests/CustomCode/PressureTests.cs | 30 +++++++++++----------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/UnitsNet.Tests/CustomCode/PressureTests.cs b/UnitsNet.Tests/CustomCode/PressureTests.cs index b0dc0f5c56..567161d08a 100644 --- a/UnitsNet.Tests/CustomCode/PressureTests.cs +++ b/UnitsNet.Tests/CustomCode/PressureTests.cs @@ -122,91 +122,91 @@ public void PressureDividedByLengthEqualsSpecificWeight() } // Pressure Measurement References [Fact] - public void ReferenceConversion_WithDefaultPressureReference_PressureReferenceIsAbsolute() + public void Reference_WithDefaultPressureReference_IsAbsolute() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); AssertEx.Equals(PressureReference.Absolute, refPressure.Reference); } [Fact] - public void ReferenceConversion_WithDefaultPressureReference_GaugeIsOneLess() + public void Gauge_WithDefaultPressureReference_IsOneLessAtmosphere() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); AssertEx.EqualTolerance(2, refPressure.Gauge.Atmospheres, AtmospheresTolerance); } [Fact] - public void ReferenceConversion_WithDefaultPressureReference_VacuumIsNegativeGaugeAsOneLess() + public void Vacuum_WithDefaultPressureReference_IsOneLessAtmosphereNegative() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); AssertEx.EqualTolerance(-2, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); } [Fact] - public void ReferenceConversion_WithDefaultPressureReference_AbsoluteIsEqual() + public void Absolute_WithDefaultPressureReference_IsEqual() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); } [Fact] - public void ReferenceConversion_WithGaugePressureReference_AbsoluteIsOneMore() + public void Absolute_WithGaugePressureReference_IsOneMore() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); AssertEx.EqualTolerance(4, refPressure.Absolute.Atmospheres, AtmospheresTolerance); } [Fact] - public void ReferenceConversion_WithGaugePressureReference_VacuumIsNegativeGauge() + public void Vacuum_WithGaugePressureReference_IsNegative() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); AssertEx.EqualTolerance(-3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); } [Fact] - public void ReferenceConversion_WithGaugePressureReference_GaugeIsEqual() + public void Gauge_WithGaugePressureReference_IsEqual() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); AssertEx.EqualTolerance(3, refPressure.Gauge.Atmospheres, AtmospheresTolerance); } [Fact] - public void ReferenceConversion_WithVacuumPressureReference_VacuumIsEqual() + public void Vacuum_WithVacuumPressureReference_IsEqual() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); AssertEx.EqualTolerance(1, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); } [Fact] - public void ReferenceConversion_WithVacuumPressureReference_GaugeIsNegativeVacuum() + public void Gauge_WithVacuumPressureReference_IsNegative() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); AssertEx.EqualTolerance(-1, refPressure.Gauge.Atmospheres, AtmospheresTolerance); } [Fact] - public void ReferenceConversion_WithVacuumPressureReferenceToGauge_AbsoluteCannotBeLessThanZero() + public void Gauge_WithVacuumPressureReference_ThrowsArgumentOutOfRangeException() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); Assert.Throws(() => refPressure.Gauge.Atmospheres); } [Fact] - public void ReferenceConversion_WithVacuumPressureReference_AbsoluteIsOneLessNegative() + public void Absolute_WithVacuumPressureReference_IsOneLessAtmosphereNegative() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); AssertEx.EqualTolerance(0, refPressure.Absolute.Atmospheres, AtmospheresTolerance); } [Fact] - public void ReferenceConversion_WithVacuumPressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() + public void Absolute_WithVacuumPressureReference_ThrowsArgumentOutOfRangeException() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); Assert.Throws(() => refPressure.Absolute.Atmospheres); } [Fact] - public void ReferenceConversion_WithAbsolutePressureReferenceToAbsolute_AbsoluteIsEqual() + public void Absolute_WithAbsolutePressureReference_IsEqual() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Absolute); AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); } [Fact] - public void ReferenceConversion_WithNegativeAbsolutePressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() + public void Absolute_WithNegativeAbsolutePressureReference_ThrowsArgumentOutOfRangeException() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Absolute); Assert.Throws(() => refPressure.Absolute.Atmospheres); } [Fact] - public void ReferenceConversion_WithNegativeGaugePressureReferenceToAbsolute_AbsoluteCannotBeLessThanZero() + public void Absolute_WithNegativeGaugePressureReference_ThrowsArgumentOutOfRangeException() { ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Gauge); Assert.Throws(() => refPressure.Absolute.Atmospheres); From ca68e3b68ffb37223b71b56d921b3bfe08f52e10 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Mon, 9 Dec 2019 10:40:18 -0600 Subject: [PATCH 13/24] Sorted unit tests in PressureTests --- UnitsNet.Tests/CustomCode/PressureTests.cs | 145 ++++++++++++--------- 1 file changed, 80 insertions(+), 65 deletions(-) diff --git a/UnitsNet.Tests/CustomCode/PressureTests.cs b/UnitsNet.Tests/CustomCode/PressureTests.cs index 567161d08a..80288d8469 100644 --- a/UnitsNet.Tests/CustomCode/PressureTests.cs +++ b/UnitsNet.Tests/CustomCode/PressureTests.cs @@ -1,16 +1,16 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using UnitsNet.CustomCode.Wrappers; +using System; using UnitsNet.CustomCode.Units; +using UnitsNet.CustomCode.Wrappers; using Xunit; -using System; namespace UnitsNet.Tests.CustomCode { public class PressureTests : PressureTestsBase { - protected override double AtmospheresInOnePascal => 9.8692*1E-6; + protected override double AtmospheresInOnePascal => 9.8692 * 1E-6; protected override double BarsInOnePascal => 1E-5; @@ -50,7 +50,7 @@ public class PressureTests : PressureTestsBase protected override double PoundsForcePerSquareInchInOnePascal => 1.450377377302092e-4; - protected override double TechnicalAtmospheresInOnePascal => 1.0197*1E-5; + protected override double TechnicalAtmospheresInOnePascal => 1.0197 * 1E-5; protected override double TonnesForcePerSquareCentimeterInOnePascal => 1.019716212977928e-8; @@ -58,7 +58,7 @@ public class PressureTests : PressureTestsBase protected override double TonnesForcePerSquareMillimeterInOnePascal => 1.019716212977928e-10; - protected override double TorrsInOnePascal => 7.5006*1E-3; + protected override double TorrsInOnePascal => 7.5006 * 1E-3; protected override double CentibarsInOnePascal => 1e-3; @@ -94,128 +94,143 @@ public class PressureTests : PressureTestsBase protected override double MillipascalsInOnePascal => 1e3; [Fact] - public void AreaTimesPressureEqualsForce() + public void Absolute_WithAbsolutePressureReference_IsEqual() { - Force force = Area.FromSquareMeters(3)*Pressure.FromPascals(20); - Assert.Equal(force, Force.FromNewtons(60)); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Absolute); + AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); } [Fact] - public void PressureTimesAreaEqualsForce() + public void Absolute_WithDefaultPressureReference_IsEqual() { - Force force = Pressure.FromPascals(20)*Area.FromSquareMeters(3); - Assert.Equal(force, Force.FromNewtons(60)); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); } [Fact] - public void PressureDividedBySpecificWeightEqualsLength() + public void Absolute_WithGaugePressureReference_IsOneMore() { - Length length = Pressure.FromPascals(20) / SpecificWeight.FromNewtonsPerCubicMeter(2); - Assert.Equal(Length.FromMeters(10), length); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); + AssertEx.EqualTolerance(4, refPressure.Absolute.Atmospheres, AtmospheresTolerance); } [Fact] - public void PressureDividedByLengthEqualsSpecificWeight() - { - SpecificWeight specificWeight = Pressure.FromPascals(20) / Length.FromMeters(2); - Assert.Equal(SpecificWeight.FromNewtonsPerCubicMeter(10), specificWeight); - } - // Pressure Measurement References - [Fact] - public void Reference_WithDefaultPressureReference_IsAbsolute() + public void Absolute_WithNegativeAbsolutePressureReference_ThrowsArgumentOutOfRangeException() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); - AssertEx.Equals(PressureReference.Absolute, refPressure.Reference); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Absolute); + Assert.Throws(() => refPressure.Absolute.Atmospheres); } + [Fact] - public void Gauge_WithDefaultPressureReference_IsOneLessAtmosphere() + public void Absolute_WithNegativeGaugePressureReference_ThrowsArgumentOutOfRangeException() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); - AssertEx.EqualTolerance(2, refPressure.Gauge.Atmospheres, AtmospheresTolerance); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Gauge); + Assert.Throws(() => refPressure.Absolute.Atmospheres); } + [Fact] - public void Vacuum_WithDefaultPressureReference_IsOneLessAtmosphereNegative() + public void Absolute_WithVacuumPressureReference_IsOneLessAtmosphereNegative() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); - AssertEx.EqualTolerance(-2, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); + AssertEx.EqualTolerance(0, refPressure.Absolute.Atmospheres, AtmospheresTolerance); } + [Fact] - public void Absolute_WithDefaultPressureReference_IsEqual() + public void Absolute_WithVacuumPressureReference_ThrowsArgumentOutOfRangeException() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); - AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); + Assert.Throws(() => refPressure.Absolute.Atmospheres); } + [Fact] - public void Absolute_WithGaugePressureReference_IsOneMore() + public void AreaTimesPressureEqualsForce() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); - AssertEx.EqualTolerance(4, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + var force = Area.FromSquareMeters(3) * Pressure.FromPascals(20); + Assert.Equal(force, Force.FromNewtons(60)); } + [Fact] - public void Vacuum_WithGaugePressureReference_IsNegative() + public void Gauge_WithDefaultPressureReference_IsOneLessAtmosphere() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); - AssertEx.EqualTolerance(-3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + AssertEx.EqualTolerance(2, refPressure.Gauge.Atmospheres, AtmospheresTolerance); } + [Fact] public void Gauge_WithGaugePressureReference_IsEqual() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); AssertEx.EqualTolerance(3, refPressure.Gauge.Atmospheres, AtmospheresTolerance); } - [Fact] - public void Vacuum_WithVacuumPressureReference_IsEqual() - { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); - AssertEx.EqualTolerance(1, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); - } + [Fact] public void Gauge_WithVacuumPressureReference_IsNegative() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); AssertEx.EqualTolerance(-1, refPressure.Gauge.Atmospheres, AtmospheresTolerance); } + [Fact] public void Gauge_WithVacuumPressureReference_ThrowsArgumentOutOfRangeException() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); Assert.Throws(() => refPressure.Gauge.Atmospheres); } + [Fact] - public void Absolute_WithVacuumPressureReference_IsOneLessAtmosphereNegative() + public void PressureDividedByLengthEqualsSpecificWeight() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); - AssertEx.EqualTolerance(0, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + var specificWeight = Pressure.FromPascals(20) / Length.FromMeters(2); + Assert.Equal(SpecificWeight.FromNewtonsPerCubicMeter(10), specificWeight); } + [Fact] - public void Absolute_WithVacuumPressureReference_ThrowsArgumentOutOfRangeException() + public void PressureDividedBySpecificWeightEqualsLength() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Vacuum); - Assert.Throws(() => refPressure.Absolute.Atmospheres); + var length = Pressure.FromPascals(20) / SpecificWeight.FromNewtonsPerCubicMeter(2); + Assert.Equal(Length.FromMeters(10), length); } + [Fact] - public void Absolute_WithAbsolutePressureReference_IsEqual() + public void PressureTimesAreaEqualsForce() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Absolute); - AssertEx.EqualTolerance(3, refPressure.Absolute.Atmospheres, AtmospheresTolerance); + var force = Pressure.FromPascals(20) * Area.FromSquareMeters(3); + Assert.Equal(force, Force.FromNewtons(60)); } + + // Pressure Measurement References [Fact] - public void Absolute_WithNegativeAbsolutePressureReference_ThrowsArgumentOutOfRangeException() + public void Reference_WithDefaultPressureReference_IsAbsolute() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Absolute); - Assert.Throws(() => refPressure.Absolute.Atmospheres); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + Equals(PressureReference.Absolute, refPressure.Reference); } + [Fact] - public void Absolute_WithNegativeGaugePressureReference_ThrowsArgumentOutOfRangeException() + public void ReferencesDoesNotContainUndefined() { - ReferencePressure refPressure = new ReferencePressure(Pressure.FromAtmospheres(-3), PressureReference.Gauge); - Assert.Throws(() => refPressure.Absolute.Atmospheres); + Assert.DoesNotContain(PressureReference.Undefined, ReferencePressure.References); } + [Fact] - public void ReferencesDoesNotContainUndefined() + public void Vacuum_WithDefaultPressureReference_IsOneLessAtmosphereNegative() { - Assert.DoesNotContain(PressureReference.Undefined, ReferencePressure.References); + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(3)); + AssertEx.EqualTolerance(-2, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + } + + [Fact] + public void Vacuum_WithGaugePressureReference_IsNegative() + { + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(3), PressureReference.Gauge); + AssertEx.EqualTolerance(-3, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); } + [Fact] + public void Vacuum_WithVacuumPressureReference_IsEqual() + { + var refPressure = new ReferencePressure(Pressure.FromAtmospheres(1), PressureReference.Vacuum); + AssertEx.EqualTolerance(1, refPressure.Vacuum.Atmospheres, AtmospheresTolerance); + } } } From a6a4b4921d98cdc57a48538f8cf20bcc3e37f2e4 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Mon, 9 Dec 2019 11:40:54 -0600 Subject: [PATCH 14/24] Refactored Pressure wrapper per review comments --- .../CustomCode/Wrappers/Pressure.Wrapper.cs | 99 ++++++++++++------- 1 file changed, 61 insertions(+), 38 deletions(-) diff --git a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs index 7213815e18..be9d3f80ea 100644 --- a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs +++ b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs @@ -1,67 +1,69 @@ using System; using System.Collections.Generic; using System.Linq; -using UnitsNet.Units; using UnitsNet.CustomCode.Units; +using UnitsNet.Units; namespace UnitsNet.CustomCode.Wrappers { /// - /// From gratestas in #422 - /// Pressure is a state function, for its measurement depends on environmental factors such as ambient pressure, elevation above sea level and local weather conditions. For two persons located in the different environment to speak of the same pressure, one must relate it to a reference. There are three basis reference: absolute, gauge, vacuum - /// Absolute is zero-referenced to the total vacuum. - /// Gauge refers to a level of the local atmospheric pressure. - /// Vacuum is the negative of the gauge. - ///Therefore, to obtain consistent and qualitative data, the reference measurement is crucial. + /// _pressure tied to a real-world reference, allowing conversion between references. + /// + /// + /// Absolute is referenced to true vacuum. + /// + /// + /// Gauge references the local atmospheric pressure. + /// + /// + /// Vacuum is the negative of the gauge. + /// + /// /// public struct ReferencePressure { /// - /// /// /// /// public ReferencePressure(Pressure pressure, PressureReference reference) { - _reference = reference; - Pressure = pressure; + Reference = reference; + _pressure = pressure; } /// - /// ctor using BaseReference of absolute to assign default _reference + /// ctor using BaseReference of absolute to assign default _reference /// /// public ReferencePressure(Pressure pressure) { - _reference = BaseReference; - Pressure = pressure; + Reference = BaseReference; + _pressure = pressure; } /// - /// The public repersentation of the measured reference this quantity was constructed with. - /// - public PressureReference Reference => _reference.GetValueOrDefault(BaseReference); - - /// - /// The measured reference this quantity was constructed with. + /// The public representation of the measured reference this quantity was constructed with. /// - private readonly PressureReference? _reference; + public PressureReference Reference { get; } /// - /// List property of reference options: Gauge, Absolute, and Vacuum + /// List property of reference options: Gauge, Absolute, and Vacuum /// - public static List References { get; } = Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] { PressureReference.Undefined }).ToList(); + public static List References { get; } = + Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); /// - /// The base reference representation of this quantity for the numeric value stored internally. All conversions go via this value. + /// The base reference representation of this quantity for the numeric value stored internally. All conversions go via + /// this value. /// - public static PressureReference BaseReference { get; } = PressureReference.Absolute; + public const PressureReference BaseReference = PressureReference.Absolute; - private Pressure Pressure { get; } + private readonly Pressure _pressure; /// /// Get Gauge Pressure. - /// It refers pressure level above Reference Pressure. + /// It refers pressure level above Reference _pressure. /// public Pressure Gauge => As(PressureReference.Gauge); @@ -73,7 +75,7 @@ public ReferencePressure(Pressure pressure) /// /// Get Vacuum Pressure. - /// It is a negative Gauge Pressure when Absolute Pressure is below Reference Pressure. + /// It is a negative Gauge _pressure when Absolute _pressure is below Reference _pressure. /// public Pressure Vacuum => As(PressureReference.Vacuum); @@ -82,7 +84,7 @@ private Pressure As(PressureReference reference) { var converted = AsBaseNumericType(reference); - return new Pressure(converted, Pressure.Unit); + return new Pressure(converted, _pressure.Unit); } private double AsBaseNumericType(PressureReference reference) @@ -90,15 +92,17 @@ private double AsBaseNumericType(PressureReference reference) var baseReferenceValue = AsBaseReference(); if (Reference == reference) - return Pressure.Value; + { + return _pressure.Value; + } var negatingValue = Reference == PressureReference.Vacuum ? -1 : 1; switch (reference) { case PressureReference.Absolute: return baseReferenceValue; - case PressureReference.Gauge: return baseReferenceValue - ReferencedPressure.ToUnit(Pressure.Unit).Value; - case PressureReference.Vacuum: return ReferencedPressure.ToUnit(Pressure.Unit).Value - negatingValue * baseReferenceValue; + case PressureReference.Gauge: return baseReferenceValue - ReferencedPressure.ToUnit(_pressure.Unit).Value; + case PressureReference.Vacuum: return ReferencedPressure.ToUnit(_pressure.Unit).Value - negatingValue * baseReferenceValue; default: throw new NotImplementedException($"Can not convert {Reference} to {reference}."); } @@ -109,20 +113,39 @@ private double AsBaseReference() switch (Reference) { case PressureReference.Absolute: - if (Pressure.Value < 0) throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); - else return Pressure.Value; + { + if (_pressure.Value < 0) + { + throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); + } + + return _pressure.Value; + } case PressureReference.Gauge: - if (Pressure.Value * -1 > ReferencedPressure.ToUnit(Pressure.Unit).Value) throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); - else return ReferencedPressure.ToUnit(Pressure.Unit).Value + Pressure.Value; + { + if (_pressure.Value * -1 > ReferencedPressure.ToUnit(_pressure.Unit).Value) + { + throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); + } + + return ReferencedPressure.ToUnit(_pressure.Unit).Value + _pressure.Value; + } case PressureReference.Vacuum: - if (Pressure.Value > ReferencedPressure.ToUnit(Pressure.Unit).Value) throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); - else return ReferencedPressure.ToUnit(Pressure.Unit).Value - Pressure.Value; + { + if (_pressure.Value > ReferencedPressure.ToUnit(_pressure.Unit).Value) + { + throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); + } + + return ReferencedPressure.ToUnit(_pressure.Unit).Value - _pressure.Value; + } default: throw new NotImplementedException($"Can not convert {Reference} to base reference."); } } + /// - /// Represents the pressure at which Pressure is referenced (1 atm default) + /// Represents the pressure at which _pressure is referenced (1 atm default) /// public static Pressure ReferencedPressure { get; } = new Pressure(1, PressureUnit.Atmosphere); } From b4fe2dd3a0e3a173aea4a14ced0a7c7a38110d50 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Mon, 9 Dec 2019 12:44:52 -0600 Subject: [PATCH 15/24] Removed Pressure Reference property from Pressure.g generated code --- UnitsNet/GeneratedCode/Quantities/Pressure.g.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs index 0936ad33f0..2b23dacf30 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs @@ -155,11 +155,6 @@ public Pressure(double value, UnitSystem unitSystem) /// public static Pressure MinValue { get; } = new Pressure(double.MinValue, BaseUnit); - /// - /// Represents the pressure at which Pressure is referenced (1 atm default) - /// - public static Pressure Reference { get; set; } = new Pressure(1, PressureUnit.Atmosphere); - /// /// The of this quantity. /// From aba8c9b0d771c8e8c8c7075cc1f8ff70f55f3109 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Mon, 9 Dec 2019 14:28:31 -0600 Subject: [PATCH 16/24] Added XML comments to Pressure.Wrapper --- .../CustomCode/Wrappers/Pressure.Wrapper.cs | 46 ++++++++++++++----- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs index be9d3f80ea..50691e1f20 100644 --- a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs +++ b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using System.Collections.Generic; using System.Linq; using UnitsNet.CustomCode.Units; @@ -7,7 +10,7 @@ namespace UnitsNet.CustomCode.Wrappers { /// - /// _pressure tied to a real-world reference, allowing conversion between references. + /// Pressure tied to a real-world reference, allowing conversion between references. /// /// /// Absolute is referenced to true vacuum. @@ -23,6 +26,8 @@ namespace UnitsNet.CustomCode.Wrappers public struct ReferencePressure { /// + /// Initializes a new instance of the struct requiring + /// and parameters /// /// /// @@ -33,7 +38,8 @@ public ReferencePressure(Pressure pressure, PressureReference reference) } /// - /// ctor using BaseReference of absolute to assign default _reference + /// Initializes a new instance of the struct requiring + /// parameter and defines the Reference to be Absolute. /// /// public ReferencePressure(Pressure pressure) @@ -43,18 +49,20 @@ public ReferencePressure(Pressure pressure) } /// - /// The public representation of the measured reference this quantity was constructed with. + /// Gets the of the /// public PressureReference Reference { get; } /// - /// List property of reference options: Gauge, Absolute, and Vacuum + /// Gets a list of options: , + /// , and /// public static List References { get; } = Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); /// - /// The base reference representation of this quantity for the numeric value stored internally. All conversions go via + /// The base reference representation of for the numeric value stored internally. All + /// conversions go via /// this value. /// public const PressureReference BaseReference = PressureReference.Absolute; @@ -62,24 +70,28 @@ public ReferencePressure(Pressure pressure) private readonly Pressure _pressure; /// - /// Get Gauge Pressure. - /// It refers pressure level above Reference _pressure. + /// Get Gauge . + /// It refers pressure level above Reference pressure. /// public Pressure Gauge => As(PressureReference.Gauge); /// - /// Get Absolute Pressure. + /// Get Absolute . /// It is zero-referenced pressure to the perfect vacuum. /// public Pressure Absolute => As(PressureReference.Absolute); /// - /// Get Vacuum Pressure. - /// It is a negative Gauge _pressure when Absolute _pressure is below Reference _pressure. + /// Get Vacuum . + /// It is a negative Gauge pressure when Absolute pressure is below Reference pressure. /// public Pressure Vacuum => As(PressureReference.Vacuum); - + /// + /// Converts to at + /// + /// The to convert to. + /// The at the specified private Pressure As(PressureReference reference) { var converted = AsBaseNumericType(reference); @@ -87,6 +99,11 @@ private Pressure As(PressureReference reference) return new Pressure(converted, _pressure.Unit); } + /// + /// Converts to at + /// + /// The to convert to. + /// The value of pressure at private double AsBaseNumericType(PressureReference reference) { var baseReferenceValue = AsBaseReference(); @@ -108,6 +125,11 @@ private double AsBaseNumericType(PressureReference reference) } } + /// + /// Converts at to at + /// + /// + /// The value of pressure at the private double AsBaseReference() { switch (Reference) From cf9e5917f4bd304275bd61e7152219faf26b4a9d Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Mon, 9 Dec 2019 15:00:47 -0600 Subject: [PATCH 17/24] Added additional constructor overload for a user-specified atmospheric pressure reference. --- .../CustomCode/Wrappers/Pressure.Wrapper.cs | 56 +++++++++++++------ 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs index 50691e1f20..d33ce141f0 100644 --- a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs +++ b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs @@ -25,27 +25,45 @@ namespace UnitsNet.CustomCode.Wrappers /// public struct ReferencePressure { + /// + /// Initializes a new instance of the struct requiring measured + /// + /// parameter. Assumes the to , with 1 atm as + /// the atmospheric . + /// + /// The measured absolute + public ReferencePressure(Pressure pressure) : this(pressure, BaseReference) + { + } + /// /// Initializes a new instance of the struct requiring - /// and parameters + /// measured and parameters. Assumes 1 atm as the atmospheric + /// . /// - /// - /// - public ReferencePressure(Pressure pressure, PressureReference reference) + /// The measured + /// + /// The referenced for the measured + /// + public ReferencePressure(Pressure pressure, PressureReference reference) : this(pressure, reference, _defaultAtmosphericPressure) { - Reference = reference; - _pressure = pressure; } /// - /// Initializes a new instance of the struct requiring - /// parameter and defines the Reference to be Absolute. + /// Initializes a new instance of the struct requiring + /// measured , , and atmospheric + /// parameters /// - /// - public ReferencePressure(Pressure pressure) + /// The measured + /// + /// The referenced for the measured + /// + /// The atmospheric where the measurement was taken. + public ReferencePressure(Pressure pressure, PressureReference reference, Pressure atmosphericPressure) { - Reference = BaseReference; + Reference = reference; _pressure = pressure; + AtmosphericPressure = atmosphericPressure; } /// @@ -118,8 +136,8 @@ private double AsBaseNumericType(PressureReference reference) switch (reference) { case PressureReference.Absolute: return baseReferenceValue; - case PressureReference.Gauge: return baseReferenceValue - ReferencedPressure.ToUnit(_pressure.Unit).Value; - case PressureReference.Vacuum: return ReferencedPressure.ToUnit(_pressure.Unit).Value - negatingValue * baseReferenceValue; + case PressureReference.Gauge: return baseReferenceValue - AtmosphericPressure.ToUnit(_pressure.Unit).Value; + case PressureReference.Vacuum: return AtmosphericPressure.ToUnit(_pressure.Unit).Value - negatingValue * baseReferenceValue; default: throw new NotImplementedException($"Can not convert {Reference} to {reference}."); } @@ -145,21 +163,21 @@ private double AsBaseReference() } case PressureReference.Gauge: { - if (_pressure.Value * -1 > ReferencedPressure.ToUnit(_pressure.Unit).Value) + if (_pressure.Value * -1 > AtmosphericPressure.ToUnit(_pressure.Unit).Value) { throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); } - return ReferencedPressure.ToUnit(_pressure.Unit).Value + _pressure.Value; + return AtmosphericPressure.ToUnit(_pressure.Unit).Value + _pressure.Value; } case PressureReference.Vacuum: { - if (_pressure.Value > ReferencedPressure.ToUnit(_pressure.Unit).Value) + if (_pressure.Value > AtmosphericPressure.ToUnit(_pressure.Unit).Value) { throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); } - return ReferencedPressure.ToUnit(_pressure.Unit).Value - _pressure.Value; + return AtmosphericPressure.ToUnit(_pressure.Unit).Value - _pressure.Value; } default: throw new NotImplementedException($"Can not convert {Reference} to base reference."); @@ -169,6 +187,8 @@ private double AsBaseReference() /// /// Represents the pressure at which _pressure is referenced (1 atm default) /// - public static Pressure ReferencedPressure { get; } = new Pressure(1, PressureUnit.Atmosphere); + public static Pressure AtmosphericPressure { get; set; } + + private static readonly Pressure _defaultAtmosphericPressure = new Pressure(1, PressureUnit.Atmosphere); } } From 28842bf2a667fb4dd83d2445f64b13bf9a64d395 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 11 Dec 2019 09:56:05 -0600 Subject: [PATCH 18/24] Updated target framework to latest minor in all projects --- CodeGen/CodeGen.csproj | 2 +- .../UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj | 2 +- .../UnitsNet.Serialization.JsonNet.Tests.csproj | 2 +- .../UnitsNet.Serialization.JsonNet.csproj | 2 +- UnitsNet.Tests/UnitsNet.Tests.csproj | 2 +- UnitsNet/UnitsNet.csproj | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CodeGen/CodeGen.csproj b/CodeGen/CodeGen.csproj index d7c7d658ab..9a8a7c74c5 100644 --- a/CodeGen/CodeGen.csproj +++ b/CodeGen/CodeGen.csproj @@ -3,7 +3,7 @@ Exe netcoreapp2.1 - 7.3 + latest diff --git a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj index bad6404562..6e724cbd19 100644 --- a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj +++ b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNet.Serialization.JsonNet.CompatibilityTests.csproj @@ -3,7 +3,7 @@ netcoreapp2.1 UnitsNet.Serialization.JsonNet.CompatibilityTests - 7.3 + latest true true diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj index 7822cbe17e..9fd7de9fab 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj @@ -3,7 +3,7 @@ netcoreapp2.1 UnitsNet.Serialization.JsonNet.Tests - 7.3 + latest true true diff --git a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj index 34fd947682..1f4061d9a7 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj +++ b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj @@ -19,7 +19,7 @@ 4.0.0.0 - 7.3 + latest UnitsNet.Serialization.JsonNet netstandard2.0;net40 true diff --git a/UnitsNet.Tests/UnitsNet.Tests.csproj b/UnitsNet.Tests/UnitsNet.Tests.csproj index 43e3cc5087..5e319ab79f 100644 --- a/UnitsNet.Tests/UnitsNet.Tests.csproj +++ b/UnitsNet.Tests/UnitsNet.Tests.csproj @@ -3,7 +3,7 @@ netcoreapp2.1 UnitsNet.Tests - 7.3 + latest true true diff --git a/UnitsNet/UnitsNet.csproj b/UnitsNet/UnitsNet.csproj index 5420f5f3cd..23fa3f55af 100644 --- a/UnitsNet/UnitsNet.csproj +++ b/UnitsNet/UnitsNet.csproj @@ -19,7 +19,7 @@ 4.0.0.0 - 7.3 + latest UnitsNet netstandard2.0;net40 true From ffa1d057c7f68511e88bb4196015701a35d5bca6 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 11 Dec 2019 10:21:11 -0600 Subject: [PATCH 19/24] Renamed files added to CustomCode, ran ReSharper rules on solution to meet code style requirements. --- CodeGen/Generators/GeneratorBase.cs | 6 +- CodeGen/Generators/QuantityJsonFilesParser.cs | 14 +- .../IQuantityTestClassGenerator.cs | 58 +- .../UnitsNetGen/QuantityGenerator.cs | 44 +- .../UnitsNetGen/QuantityTypeGenerator.cs | 6 + .../UnitsNetGen/StaticQuantityGenerator.cs | 3 + .../UnitAbbreviationsCacheGenerator.cs | 3 + .../UnitsNetGen/UnitConverterGenerator.cs | 21 +- .../UnitsNetGen/UnitTestBaseClassGenerator.cs | 84 ++- .../UnitsNetGen/UnitTestStubGenerator.cs | 3 + .../UnitsNetGen/UnitTypeGenerator.cs | 9 +- .../UnitsNetWrcGen/QuantityGenerator.cs | 65 +- .../UnitsNetWrcGen/QuantityTypeGenerator.cs | 6 + .../UnitsNetWrcGen/StaticQuantityGenerator.cs | 33 +- .../UnitAbbreviationsCacheGenerator.cs | 3 + .../UnitsNetWrcGen/UnitTypeGenerator.cs | 9 +- CodeGen/Helpers/MyTextWriter.cs | 15 +- CodeGen/Helpers/StringExtensions.cs | 4 +- CodeGen/JsonTypes/BaseDimensions.cs | 6 + CodeGen/JsonTypes/BaseUnits.cs | 6 + CodeGen/JsonTypes/Prefix.cs | 5 +- CodeGen/JsonTypes/Quantity.cs | 1 - CodeGen/PrefixInfo.cs | 39 +- CodeGen/Program.cs | 7 +- Common/UnitDefinitions/Acceleration.json | 19 +- Common/UnitDefinitions/AmountOfSubstance.json | 11 +- Common/UnitDefinitions/AmplitudeRatio.json | 8 +- Common/UnitDefinitions/Angle.json | 27 +- Common/UnitDefinitions/ApparentEnergy.json | 7 +- Common/UnitDefinitions/ApparentPower.json | 7 +- Common/UnitDefinitions/Area.json | 51 +- Common/UnitDefinitions/AreaDensity.json | 2 +- .../UnitDefinitions/AreaMomentOfInertia.json | 12 +- Common/UnitDefinitions/BitRate.json | 11 +- .../BrakeSpecificFuelConsumption.json | 9 +- Common/UnitDefinitions/Capacitance.json | 4 +- .../CoefficientOfThermalExpansion.json | 6 +- Common/UnitDefinitions/Density.json | 50 +- Common/UnitDefinitions/Duration.json | 35 +- Common/UnitDefinitions/DynamicViscosity.json | 19 +- .../UnitDefinitions/ElectricAdmittance.json | 7 +- Common/UnitDefinitions/ElectricCharge.json | 9 +- .../ElectricChargeDensity.json | 2 +- .../UnitDefinitions/ElectricConductance.json | 7 +- .../UnitDefinitions/ElectricConductivity.json | 9 +- Common/UnitDefinitions/ElectricCurrent.json | 7 +- .../ElectricCurrentDensity.json | 6 +- .../ElectricCurrentGradient.json | 2 +- Common/UnitDefinitions/ElectricField.json | 5 +- .../UnitDefinitions/ElectricInductance.json | 4 +- Common/UnitDefinitions/ElectricPotential.json | 9 +- .../UnitDefinitions/ElectricPotentialAc.json | 4 +- .../UnitDefinitions/ElectricPotentialDc.json | 4 +- .../UnitDefinitions/ElectricResistance.json | 7 +- .../UnitDefinitions/ElectricResistivity.json | 11 +- .../ElectricSurfaceChargeDensity.json | 9 +- Common/UnitDefinitions/Energy.json | 47 +- Common/UnitDefinitions/Entropy.json | 17 +- Common/UnitDefinitions/Force.json | 37 +- Common/UnitDefinitions/ForceChangeRate.json | 11 +- Common/UnitDefinitions/ForcePerLength.json | 14 +- Common/UnitDefinitions/Frequency.json | 14 +- Common/UnitDefinitions/FuelEfficiency.json | 86 ++- Common/UnitDefinitions/HeatFlux.json | 26 +- .../HeatTransferCoefficient.json | 9 +- Common/UnitDefinitions/Illuminance.json | 4 +- Common/UnitDefinitions/Information.json | 11 +- Common/UnitDefinitions/Irradiance.json | 8 +- Common/UnitDefinitions/Irradiation.json | 17 +- .../UnitDefinitions/KinematicViscosity.json | 15 +- Common/UnitDefinitions/LapseRate.json | 5 +- Common/UnitDefinitions/Length.json | 72 +- Common/UnitDefinitions/Level.json | 7 +- Common/UnitDefinitions/LinearDensity.json | 9 +- Common/UnitDefinitions/Luminosity.json | 9 +- Common/UnitDefinitions/LuminousFlux.json | 2 +- Common/UnitDefinitions/LuminousIntensity.json | 5 +- Common/UnitDefinitions/MagneticField.json | 7 +- Common/UnitDefinitions/MagneticFlux.json | 5 +- Common/UnitDefinitions/Magnetization.json | 5 +- Common/UnitDefinitions/Mass.json | 74 +- Common/UnitDefinitions/MassConcentration.json | 51 +- Common/UnitDefinitions/MassFlow.json | 45 +- Common/UnitDefinitions/MassFlux.json | 4 +- Common/UnitDefinitions/MassFraction.json | 22 +- .../UnitDefinitions/MassMomentOfInertia.json | 40 +- Common/UnitDefinitions/MolarEnergy.json | 6 +- Common/UnitDefinitions/MolarEntropy.json | 6 +- Common/UnitDefinitions/MolarMass.json | 17 +- Common/UnitDefinitions/Molarity.json | 11 +- Common/UnitDefinitions/Permeability.json | 5 +- Common/UnitDefinitions/Permittivity.json | 5 +- Common/UnitDefinitions/Power.json | 25 +- Common/UnitDefinitions/PowerDensity.json | 16 +- Common/UnitDefinitions/PowerRatio.json | 4 +- Common/UnitDefinitions/Pressure.json | 87 +-- .../UnitDefinitions/PressureChangeRate.json | 21 +- Common/UnitDefinitions/Ratio.json | 15 +- Common/UnitDefinitions/RatioChangeRate.json | 5 +- Common/UnitDefinitions/ReactiveEnergy.json | 7 +- Common/UnitDefinitions/ReactivePower.json | 7 +- .../RotationalAcceleration.json | 8 +- Common/UnitDefinitions/RotationalSpeed.json | 25 +- .../UnitDefinitions/RotationalStiffness.json | 4 +- .../RotationalStiffnessPerLength.json | 4 +- Common/UnitDefinitions/SolidAngle.json | 5 +- Common/UnitDefinitions/SpecificEnergy.json | 15 +- Common/UnitDefinitions/SpecificEntropy.json | 17 +- Common/UnitDefinitions/SpecificVolume.json | 11 +- Common/UnitDefinitions/SpecificWeight.json | 37 +- Common/UnitDefinitions/Speed.json | 43 +- Common/UnitDefinitions/Temperature.json | 21 +- .../TemperatureChangeRate.json | 9 +- Common/UnitDefinitions/TemperatureDelta.json | 16 +- .../UnitDefinitions/ThermalConductivity.json | 4 +- Common/UnitDefinitions/ThermalResistance.json | 11 +- Common/UnitDefinitions/Torque.json | 39 +- Common/UnitDefinitions/TorquePerLength.json | 36 +- Common/UnitDefinitions/VitaminA.json | 2 +- Common/UnitDefinitions/Volume.json | 97 +-- .../UnitDefinitions/VolumeConcentration.json | 29 +- Common/UnitDefinitions/VolumeFlow.json | 91 +-- Common/UnitDefinitions/VolumePerLength.json | 8 +- UnitsNet.Benchmark/Program.cs | 11 +- .../UnitsNetJsonConverterTests.cs | 343 ++++----- .../UnitsNetJsonConverterTests.cs | 339 ++++----- .../Internal/ReflectionHelper.cs | 17 +- .../UnitsNetJsonConverter.cs | 69 +- UnitsNet.Tests/AssemblyAttributeTests.cs | 20 +- UnitsNet.Tests/AssertEx.cs | 23 +- UnitsNet.Tests/BaseDimensionsTests.cs | 691 +++++++++--------- UnitsNet.Tests/BaseUnitsTests.cs | 152 ++-- .../CustomCode/AccelerationTests.cs | 2 +- .../CustomCode/AmplitudeRatioTests.cs | 22 +- UnitsNet.Tests/CustomCode/AngleTests.cs | 4 +- UnitsNet.Tests/CustomCode/AreaTests.cs | 53 +- .../BrakeSpecificFuelConsumptionTests.cs | 15 +- UnitsNet.Tests/CustomCode/DensityTests.cs | 32 +- UnitsNet.Tests/CustomCode/DurationTests.cs | 164 ++--- .../CustomCode/DynamicViscosityTests.cs | 3 +- .../CustomCode/ElectricCurrentTests.cs | 2 +- .../CustomCode/ElectricPotentialTests.cs | 4 +- .../CustomCode/ElectricResistanceTests.cs | 2 +- UnitsNet.Tests/CustomCode/EnergyTests.cs | 12 +- UnitsNet.Tests/CustomCode/ForceTests.cs | 40 +- UnitsNet.Tests/CustomCode/FrequencyTests.cs | 2 +- UnitsNet.Tests/CustomCode/IQuantityTests.cs | 24 +- UnitsNet.Tests/CustomCode/InformationTests.cs | 48 +- .../CustomCode/KinematicViscosityTests.cs | 24 +- UnitsNet.Tests/CustomCode/KnownQuantities.cs | 5 +- .../CustomCode/LengthTests.FeetInches.cs | 38 +- UnitsNet.Tests/CustomCode/LengthTests.cs | 102 +-- UnitsNet.Tests/CustomCode/LevelTests.cs | 4 +- UnitsNet.Tests/CustomCode/MassFlowTests.cs | 58 +- UnitsNet.Tests/CustomCode/MassTests.cs | 44 +- UnitsNet.Tests/CustomCode/ParseTests.cs | 42 +- UnitsNet.Tests/CustomCode/PowerRatioTests.cs | 20 +- UnitsNet.Tests/CustomCode/PowerTests.cs | 56 +- .../CustomCode/PressureChangeRateTests.cs | 2 +- .../CustomCode/RotationalSpeedTests.cs | 8 +- .../CustomCode/SpecificEnergyTests.cs | 28 +- .../CustomCode/SpecificWeightTests.cs | 14 +- UnitsNet.Tests/CustomCode/SpeedTests.cs | 42 +- UnitsNet.Tests/CustomCode/StonePoundsTests.cs | 40 +- .../CustomCode/TemperatureChangeRateTests.cs | 2 +- UnitsNet.Tests/CustomCode/TemperatureTests.cs | 111 ++- UnitsNet.Tests/CustomCode/TorqueTests.cs | 4 +- UnitsNet.Tests/CustomCode/VolumeTests.cs | 44 +- UnitsNet.Tests/CustomQuantities/HowMuch.cs | 12 +- .../CustomQuantities/HowMuchUnit.cs | 5 +- UnitsNet.Tests/DecimalOverloadTests.cs | 12 +- UnitsNet.Tests/DummyIQuantity.cs | 7 +- UnitsNet.Tests/EnumUtils.cs | 2 +- UnitsNet.Tests/GeneratedQuantityCodeTests.cs | 11 +- .../Helpers/TypeDescriptorContext.cs | 57 +- UnitsNet.Tests/IntOverloadTests.cs | 4 +- UnitsNet.Tests/InterUnitConversionTests.cs | 8 +- UnitsNet.Tests/LongOverloadTests.cs | 4 +- UnitsNet.Tests/QuantityIConvertibleTests.cs | 13 +- UnitsNet.Tests/QuantityIFormattableTests.cs | 48 +- UnitsNet.Tests/QuantityInfoTest.cs | 167 +++-- UnitsNet.Tests/QuantityParserTests.cs | 5 +- UnitsNet.Tests/QuantityTest.cs | 78 +- UnitsNet.Tests/QuantityTests.Ctor.cs | 203 ++--- UnitsNet.Tests/QuantityTests.ToString.cs | 82 +-- UnitsNet.Tests/QuantityTests.cs | 44 +- UnitsNet.Tests/QuantityTypeConverterTest.cs | 263 ++++--- .../UnitAbbreviationsCacheFixture.cs | 5 +- UnitsNet.Tests/UnitAbbreviationsCacheTests.cs | 133 ++-- UnitsNet.Tests/UnitConverterTest.cs | 225 +++--- UnitsNet.Tests/UnitMathTests.cs | 71 +- UnitsNet.Tests/UnitParserTests.cs | 92 +-- UnitsNet.Tests/UnitSystemTests.cs | 85 ++- UnitsNet/AssemblyInfo.cs | 5 +- UnitsNet/BaseDimensions.cs | 165 +++-- UnitsNet/BaseUnits.cs | 189 ++--- UnitsNet/Comparison.cs | 6 + UnitsNet/ComparisonType.cs | 6 +- UnitsNet/CustomCode/GlobalConfiguration.cs | 2 +- .../Quantities/Acceleration.extra.cs | 6 +- .../Quantities/AmountOfSubstance.extra.cs | 22 +- .../Quantities/AmplitudeRatio.extra.cs | 8 +- UnitsNet/CustomCode/Quantities/Angle.extra.cs | 2 +- UnitsNet/CustomCode/Quantities/Area.extra.cs | 6 +- .../Quantities/AreaMomentOfInertia.extra.cs | 4 +- .../BrakeSpecificFuelConsumption.extra.cs | 15 +- .../CustomCode/Quantities/Density.extra.cs | 18 +- .../CustomCode/Quantities/Duration.extra.cs | 37 +- .../Quantities/DynamicViscosity.extra.cs | 2 +- .../Quantities/ElectricCurrent.extra.cs | 5 +- .../Quantities/ElectricPotential.extra.cs | 13 +- .../Quantities/ElectricResistance.extra.cs | 5 +- UnitsNet/CustomCode/Quantities/Force.extra.cs | 18 +- .../Quantities/ForcePerLength.extra.cs | 6 +- .../CustomCode/Quantities/HeatFlux.extra.cs | 2 +- .../Quantities/KinematicViscosity.extra.cs | 12 +- .../CustomCode/Quantities/LapseRate.extra.cs | 6 +- .../CustomCode/Quantities/Length.extra.cs | 98 +-- UnitsNet/CustomCode/Quantities/Level.extra.cs | 9 +- UnitsNet/CustomCode/Quantities/Mass.extra.cs | 36 +- .../Quantities/MassConcentration.extra.cs | 23 +- .../CustomCode/Quantities/MassFlow.extra.cs | 22 +- .../CustomCode/Quantities/MassFlux.extra.cs | 6 +- .../Quantities/MassFraction.extra.cs | 22 +- .../CustomCode/Quantities/Molarity.extra.cs | 37 +- UnitsNet/CustomCode/Quantities/Power.extra.cs | 26 +- .../CustomCode/Quantities/PowerRatio.extra.cs | 3 +- .../CustomCode/Quantities/Pressure.extra.cs | 14 +- .../Quantities/RotationalSpeed.extra.cs | 8 +- .../Quantities/RotationalStiffness.extra.cs | 12 +- .../RotationalStiffnessPerLength.extra.cs | 6 +- .../Quantities/SpecificEnergy.extra.cs | 16 +- .../Quantities/SpecificVolume.extra.cs | 4 +- .../Quantities/SpecificWeight.extra.cs | 16 +- UnitsNet/CustomCode/Quantities/Speed.extra.cs | 20 +- .../Quantities/Temperature.extra.cs | 4 +- .../Quantities/TemperatureDelta.extra.cs | 6 +- .../CustomCode/Quantities/Torque.extra.cs | 8 +- .../CustomCode/Quantities/Volume.extra.cs | 10 +- .../Quantities/VolumeConcentration.extra.cs | 33 +- .../CustomCode/Quantities/VolumeFlow.extra.cs | 12 +- UnitsNet/CustomCode/Quantity.cs | 44 +- UnitsNet/CustomCode/QuantityParser.cs | 37 +- UnitsNet/CustomCode/UnitAbbreviationsCache.cs | 203 +++-- UnitsNet/CustomCode/UnitParser.cs | 92 ++- .../CustomCode/UnitValueAbbreviationLookup.cs | 33 +- ...PressureUnit.g.cs => PressureReference.cs} | 0 ...essure.Wrapper.cs => ReferencePressure.cs} | 30 +- UnitsNet/IQuantity.cs | 89 ++- .../ReflectionBridgeExtensions.cs | 10 +- UnitsNet/QuantityFormatter.cs | 57 +- UnitsNet/QuantityInfo.cs | 68 +- UnitsNet/QuantityTypeConverter.cs | 152 ++-- UnitsNet/QuantityValue.cs | 43 +- UnitsNet/UnitConverter.cs | 148 ++-- UnitsNet/UnitFormatter.cs | 8 +- UnitsNet/UnitInfo.cs | 16 +- UnitsNet/UnitMath.cs | 5 +- UnitsNet/UnitSystem.cs | 65 +- 259 files changed, 4652 insertions(+), 4154 deletions(-) rename UnitsNet/CustomCode/Units/{PressureUnit.g.cs => PressureReference.cs} (100%) rename UnitsNet/CustomCode/Wrappers/{Pressure.Wrapper.cs => ReferencePressure.cs} (97%) diff --git a/CodeGen/Generators/GeneratorBase.cs b/CodeGen/Generators/GeneratorBase.cs index 53c9a23f7f..4f16c11375 100644 --- a/CodeGen/Generators/GeneratorBase.cs +++ b/CodeGen/Generators/GeneratorBase.cs @@ -7,9 +7,6 @@ namespace CodeGen.Generators { internal abstract class GeneratorBase { - protected readonly MyTextWriter Writer = new MyTextWriter(); - public abstract string Generate(); - public const string GeneratedFileHeader = @"//------------------------------------------------------------------------------ // // This code was generated by \generate-code.bat. @@ -29,5 +26,8 @@ internal abstract class GeneratorBase // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. "; + + protected readonly MyTextWriter Writer = new MyTextWriter(); + public abstract string Generate(); } } diff --git a/CodeGen/Generators/QuantityJsonFilesParser.cs b/CodeGen/Generators/QuantityJsonFilesParser.cs index 3ab95e8d4b..5cd40388f0 100644 --- a/CodeGen/Generators/QuantityJsonFilesParser.cs +++ b/CodeGen/Generators/QuantityJsonFilesParser.cs @@ -110,13 +110,9 @@ private static Localization[] GetLocalizationForPrefixUnit(IEnumerable { - if (loc.TryGetAbbreviationsForPrefix(prefixInfo.Prefix, out string[] unitAbbreviationsForPrefix)) + if (loc.TryGetAbbreviationsForPrefix(prefixInfo.Prefix, out var unitAbbreviationsForPrefix)) { - return new Localization - { - Culture = loc.Culture, - Abbreviations = unitAbbreviationsForPrefix - }; + return new Localization {Culture = loc.Culture, Abbreviations = unitAbbreviationsForPrefix}; } // No prefix unit abbreviations are specified, so fall back to prepending the default SI prefix to each unit abbreviation: @@ -124,11 +120,7 @@ private static Localization[] GetLocalizationForPrefixUnit(IEnumerable $"{prefix}{unitAbbreviation}").ToArray(); - return new Localization - { - Culture = loc.Culture, - Abbreviations = unitAbbreviationsForPrefix - }; + return new Localization {Culture = loc.Culture, Abbreviations = unitAbbreviationsForPrefix}; }).ToArray(); } } diff --git a/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs index 5469bfc504..f36c1acd31 100644 --- a/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs @@ -1,7 +1,6 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using System; using System.Linq; using CodeGen.JsonTypes; @@ -19,23 +18,23 @@ public IQuantityTestClassGenerator(Quantity[] quantities) public override string Generate() { Writer.WL(GeneratedFileHeader); - Writer.WL($@" + Writer.WL(@" using System; using UnitsNet.Units; using Xunit; namespace UnitsNet.Tests -{{ +{ public partial class IQuantityTests - {{ + { [Fact] public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() - {{ + { void Assertion(int expectedValue, Enum expectedUnit, IQuantity quantity) - {{ + { Assert.Equal(expectedUnit, quantity.Unit); Assert.Equal(expectedValue, quantity.Value); - }} + } "); foreach (var quantity in _quantities) { @@ -47,40 +46,53 @@ void Assertion(int expectedValue, Enum expectedUnit, IQuantity quantity) Writer.WL($@" Assertion(3, {unitEnumNameAndValue}, Quantity.From(3, {unitEnumNameAndValue}));"); } - Writer.WL($@" - }} + + Writer.WL(@" + } [Fact] public void QuantityInfo_IsSameAsStaticInfoProperty() - {{ + { void Assertion(QuantityInfo expected, IQuantity quantity) => Assert.Same(expected, quantity.QuantityInfo); "); - foreach (var quantity in _quantities) Writer.WL($@" + foreach (var quantity in _quantities) + { + Writer.WL($@" Assertion({quantity.Name}.Info, {quantity.Name}.Zero);"); - Writer.WL($@" - }} + } + + Writer.WL(@" + } [Fact] public void Type_EqualsStaticQuantityTypeProperty() - {{ + { void Assertion(QuantityType expected, IQuantity quantity) => Assert.Equal(expected, quantity.Type); "); - foreach (var quantity in _quantities) Writer.WL($@" + foreach (var quantity in _quantities) + { + Writer.WL($@" Assertion({quantity.Name}.QuantityType, {quantity.Name}.Zero);"); - Writer.WL($@" - }} + } + + Writer.WL(@" + } [Fact] public void Dimensions_IsSameAsStaticBaseDimensions() - {{ + { void Assertion(BaseDimensions expected, IQuantity quantity) => Assert.Equal(expected, quantity.Dimensions); "); - foreach (var quantity in _quantities) Writer.WL($@" + foreach (var quantity in _quantities) + { + Writer.WL($@" Assertion({quantity.Name}.BaseDimensions, {quantity.Name}.Zero);"); - Writer.WL($@" - }} - }} -}}"); + } + + Writer.WL(@" + } + } +}"); return Writer.ToString(); } diff --git a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs index caff760f4a..3ac24e78e8 100644 --- a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs @@ -10,12 +10,12 @@ namespace CodeGen.Generators.UnitsNetGen { internal class QuantityGenerator : GeneratorBase { - private readonly Quantity _quantity; + private readonly Unit _baseUnit; private readonly bool _isDimensionless; + private readonly Quantity _quantity; private readonly string _unitEnumName; private readonly string _valueType; - private readonly Unit _baseUnit; public QuantityGenerator(Quantity quantity) { @@ -28,16 +28,15 @@ public QuantityGenerator(Quantity quantity) _valueType = quantity.BaseType; _unitEnumName = $"{quantity.Name}Unit"; - BaseDimensions baseDimensions = quantity.BaseDimensions; + var baseDimensions = quantity.BaseDimensions; _isDimensionless = baseDimensions == null || - baseDimensions.L == 0 && - baseDimensions.M == 0 && - baseDimensions.T == 0 && - baseDimensions.I == 0 && - baseDimensions.Θ == 0 && - baseDimensions.N == 0 && - baseDimensions.J == 0; - + baseDimensions.L == 0 && + baseDimensions.M == 0 && + baseDimensions.T == 0 && + baseDimensions.I == 0 && + baseDimensions.Θ == 0 && + baseDimensions.N == 0 && + baseDimensions.J == 0; } public override string Generate() @@ -94,9 +93,9 @@ public partial struct {_quantity.Name} : IQuantity<{_unitEnumName}>, IEquatable< GenerateToString(); GenerateIConvertibleMethods(); - Writer.WL($@" - }} -}}"); + Writer.WL(@" + } +}"); return Writer.ToString(); } @@ -131,8 +130,7 @@ private void GenerateStaticConstructor() var baseUnitsCtorArgs = string.Join(", ", new[] { - baseUnits.L != null ? $"length: LengthUnit.{baseUnits.L}" : null, - baseUnits.M != null ? $"mass: MassUnit.{baseUnits.M}" : null, + baseUnits.L != null ? $"length: LengthUnit.{baseUnits.L}" : null, baseUnits.M != null ? $"mass: MassUnit.{baseUnits.M}" : null, baseUnits.T != null ? $"time: DurationUnit.{baseUnits.T}" : null, baseUnits.I != null ? $"current: ElectricCurrentUnit.{baseUnits.I}" : null, baseUnits.Θ != null ? $"temperature: TemperatureUnit.{baseUnits.Θ}" : null, @@ -263,9 +261,11 @@ private void GenerateProperties() // Need to provide explicit interface implementation for decimal quantities like Information if (_quantity.BaseType != "double") + { Writer.WL(@" double IQuantity.Value => (double) _value; "); + } Writer.WL($@" Enum IQuantity.Unit => Unit; @@ -538,7 +538,9 @@ public static bool TryParseUnit(string str, IFormatProvider provider, out {_unit private void GenerateArithmeticOperators() { if (!_quantity.GenerateArithmetic) + { return; + } // Logarithmic units required different arithmetic if (_quantity.Logarithmic) @@ -1028,7 +1030,7 @@ public string ToString(string format, IFormatProvider formatProvider) private void GenerateIConvertibleMethods() { - Writer.WL($@" + Writer.WL($@" #region IConvertible Methods TypeCode IConvertible.GetTypeCode() @@ -1128,15 +1130,15 @@ ulong IConvertible.ToUInt64(IFormatProvider provider) #endregion"); } - /// + /// internal static string GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText); - /// + /// internal static string GetObsoleteAttributeOrNull(Unit unit) => GetObsoleteAttributeOrNull(unit.ObsoleteText); /// - /// Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string - /// It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats + /// Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string + /// It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats /// private static string GetObsoleteAttributeOrNull(string obsoleteText) => string.IsNullOrWhiteSpace(obsoleteText) ? null diff --git a/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs b/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs index b105c5cbc6..a49f858f9c 100644 --- a/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using CodeGen.JsonTypes; namespace CodeGen.Generators.UnitsNetGen @@ -30,8 +33,11 @@ public enum QuantityType #pragma warning disable CS1591 Undefined = 0,"); foreach (var quantity in _quantities) + { Writer.WL($@" {quantity.Name},"); + } + Writer.WL(@" // Missing XML comment for public type or member #pragma warning restore CS1591 diff --git a/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs index 25d9143e49..e21e45e2c0 100644 --- a/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using CodeGen.Helpers; using CodeGen.JsonTypes; diff --git a/CodeGen/Generators/UnitsNetGen/UnitAbbreviationsCacheGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitAbbreviationsCacheGenerator.cs index 26189a0172..269a128a06 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitAbbreviationsCacheGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitAbbreviationsCacheGenerator.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using System.Linq; using CodeGen.JsonTypes; diff --git a/CodeGen/Generators/UnitsNetGen/UnitConverterGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitConverterGenerator.cs index 09047b06e9..78c53e9a12 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitConverterGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitConverterGenerator.cs @@ -1,7 +1,6 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using CodeGen.Helpers; using CodeGen.JsonTypes; namespace CodeGen.Generators.UnitsNetGen @@ -18,24 +17,24 @@ public UnitConverterGenerator(Quantity[] quantities) public override string Generate() { Writer.WL(GeneratedFileHeader); - Writer.WL($@" + Writer.WL(@" using UnitsNet.Units; // ReSharper disable RedundantCommaInArrayInitializer // ReSharper disable once CheckNamespace namespace UnitsNet -{{ +{ public sealed partial class UnitConverter - {{ + { /// /// Registers the default conversion functions in the given instance. /// /// The to register the default conversion functions in. public static void RegisterDefaultConversions(UnitConverter unitConverter) - {{"); - foreach (Quantity quantity in _quantities) - foreach (Unit unit in quantity.Units) + {"); + foreach (var quantity in _quantities) + foreach (var unit in quantity.Units) { Writer.WL(quantity.BaseUnit == unit.SingularName ? $@" @@ -45,10 +44,10 @@ public static void RegisterDefaultConversions(UnitConverter unitConverter) unitConverter.SetConversionFunction<{quantity.Name}>({quantity.Name}Unit.{unit.SingularName}, {quantity.Name}.BaseUnit, q => q.ToBaseUnit());"); } - Writer.WL($@" - }} - }} -}}"); + Writer.WL(@" + } + } +}"); return Writer.ToString(); } diff --git a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs index 41f6edb63f..2ffa35f596 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using System; using System.Linq; using CodeGen.JsonTypes; @@ -6,8 +9,8 @@ namespace CodeGen.Generators.UnitsNetGen { internal class UnitTestBaseClassGenerator : GeneratorBase { - private readonly Quantity _quantity; private readonly Unit _baseUnit; + private readonly Quantity _quantity; private readonly string _unitEnumName; public UnitTestBaseClassGenerator(Quantity quantity) @@ -42,14 +45,22 @@ namespace UnitsNet.Tests // ReSharper disable once PartialTypeWithSinglePart public abstract partial class {_quantity.Name}TestsBase {{"); - foreach (var unit in _quantity.Units) Writer.WL($@" + foreach (var unit in _quantity.Units) + { + Writer.WL($@" protected abstract double {unit.PluralName}InOne{_baseUnit.SingularName} {{ get; }}"); + } - Writer.WL(""); - Writer.WL($@" + Writer.WL(); + Writer.WL(@" // ReSharper disable VirtualMemberNeverOverriden.Global"); - foreach (var unit in _quantity.Units) Writer.WL($@" - protected virtual double {unit.PluralName}Tolerance {{ get {{ return 1e-5; }} }}"); Writer.WL($@" + foreach (var unit in _quantity.Units) + { + Writer.WL($@" + protected virtual double {unit.PluralName}Tolerance {{ get {{ return 1e-5; }} }}"); + } + + Writer.WL($@" // ReSharper restore VirtualMemberNeverOverriden.Global [Fact] @@ -58,7 +69,9 @@ public void Ctor_WithUndefinedUnit_ThrowsArgumentException() Assert.Throws(() => new {_quantity.Name}(({_quantity.BaseType})0.0, {_unitEnumName}.Undefined)); }} "); - if (_quantity.BaseType == "double") Writer.WL($@" + if (_quantity.BaseType == "double") + { + Writer.WL($@" [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() {{ @@ -71,27 +84,40 @@ public void Ctor_WithNaNValue_ThrowsArgumentException() {{ Assert.Throws(() => new {_quantity.Name}(double.NaN, {_unitEnumName}.{_baseUnit.SingularName})); }} -"); Writer.WL($@" +"); + } + + Writer.WL($@" [Fact] public void {_baseUnit.SingularName}To{_quantity.Name}Units() {{ {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);"); - foreach (var unit in _quantity.Units) Writer.WL($@" + foreach (var unit in _quantity.Units) + { + Writer.WL($@" AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, {baseUnitVariableName}.{unit.PluralName}, {unit.PluralName}Tolerance);"); - Writer.WL($@" - }} + } + + Writer.WL(@" + } [Fact] public void FromValueAndUnit() - {{"); - foreach (var unit in _quantity.Units) Writer.WL($@" + {"); + foreach (var unit in _quantity.Units) + { + Writer.WL($@" AssertEx.EqualTolerance(1, {_quantity.Name}.From(1, {_unitEnumName}.{unit.SingularName}).{unit.PluralName}, {unit.PluralName}Tolerance);"); - Writer.WL($@" - }} + } + + Writer.WL(@" + } "); - if (_quantity.BaseType == "double") Writer.WL($@" + if (_quantity.BaseType == "double") + { + Writer.WL($@" [Fact] public void From{_baseUnit.PluralName}_WithInfinityValue_ThrowsArgumentException() {{ @@ -104,14 +130,21 @@ public void FromValueAndUnit() {{ Assert.Throws(() => {_quantity.Name}.From{_baseUnit.PluralName}(double.NaN)); }} -"); Writer.WL($@" +"); + } + + Writer.WL($@" [Fact] public void As() {{ var {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);"); - foreach (var unit in _quantity.Units) Writer.WL($@" + foreach (var unit in _quantity.Units) + { + Writer.WL($@" AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, {baseUnitVariableName}.As({_unitEnumName}.{unit.SingularName}), {unit.PluralName}Tolerance);"); + } + Writer.WL($@" }} @@ -123,12 +156,13 @@ public void ToUnit() { var asQuantityVariableName = $"{unit.SingularName.ToLowerInvariant()}Quantity"; - Writer.WL(""); + Writer.WL(); Writer.WL($@" var {asQuantityVariableName} = {baseUnitVariableName}.ToUnit({_unitEnumName}.{unit.SingularName}); AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, (double){asQuantityVariableName}.Value, {unit.PluralName}Tolerance); Assert.Equal({_unitEnumName}.{unit.SingularName}, {asQuantityVariableName}.Unit);"); } + Writer.WL($@" }} @@ -136,10 +170,14 @@ public void ToUnit() public void ConversionRoundTrip() {{ {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);"); - foreach (var unit in _quantity.Units) Writer.WL($@" + foreach (var unit in _quantity.Units) + { + Writer.WL($@" AssertEx.EqualTolerance(1, {_quantity.Name}.From{unit.PluralName}({baseUnitVariableName}.{unit.PluralName}).{_baseUnit.PluralName}, {unit.PluralName}Tolerance);"); - Writer.WL($@" - }} + } + + Writer.WL(@" + } "); if (_quantity.Logarithmic) { @@ -182,7 +220,7 @@ public void ArithmeticOperators() } else { - Writer.WL(""); + Writer.WL(); } Writer.WL($@" diff --git a/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs index 3580502e0b..5dbff53de5 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using CodeGen.JsonTypes; namespace CodeGen.Generators.UnitsNetGen diff --git a/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs index eaf6220511..55226e6e65 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using CodeGen.Helpers; using CodeGen.JsonTypes; @@ -50,11 +53,11 @@ public enum {_unitEnumName} {unit.SingularName},"); } - Writer.WL($@" - }} + Writer.WL(@" + } #pragma warning restore 1591 -}}"); +}"); return Writer.ToString(); } } diff --git a/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs index fc3507efa9..4d9b012d2e 100644 --- a/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs @@ -10,12 +10,12 @@ namespace CodeGen.Generators.UnitsNetWrcGen { internal class QuantityGenerator : GeneratorBase { - private readonly Quantity _quantity; + private readonly Unit _baseUnit; private readonly bool _isDimensionless; + private readonly Quantity _quantity; private readonly string _unitEnumName; private readonly string _valueType; - private readonly Unit _baseUnit; public QuantityGenerator(Quantity quantity) { @@ -28,16 +28,15 @@ public QuantityGenerator(Quantity quantity) _valueType = quantity.BaseType; _unitEnumName = $"{quantity.Name}Unit"; - BaseDimensions baseDimensions = quantity.BaseDimensions; + var baseDimensions = quantity.BaseDimensions; _isDimensionless = baseDimensions == null || - baseDimensions.L == 0 && - baseDimensions.M == 0 && - baseDimensions.T == 0 && - baseDimensions.I == 0 && - baseDimensions.Θ == 0 && - baseDimensions.N == 0 && - baseDimensions.J == 0; - + baseDimensions.L == 0 && + baseDimensions.M == 0 && + baseDimensions.T == 0 && + baseDimensions.I == 0 && + baseDimensions.Θ == 0 && + baseDimensions.N == 0 && + baseDimensions.J == 0; } public override string Generate() @@ -94,13 +93,13 @@ public sealed partial class {_quantity.Name} : IQuantity GenerateConversionMethods(); GenerateToString(); - Writer.WL($@" + Writer.WL(@" private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - {{ + { return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - }} - }} -}}"); + } + } +}"); return Writer.ToString(); } @@ -155,9 +154,9 @@ private void GenerateInstanceConstructors() _value = Guard.EnsureValidNumber(value, nameof(value));" : @" _value = value;"); - Writer.WL($@" + Writer.WL(@" _unit = unit; - }} + } "); } @@ -212,7 +211,7 @@ private void GenerateStaticProperties() private void GenerateProperties() { - Writer.WL($@" + Writer.WL(@" #region Properties /// @@ -672,7 +671,7 @@ public double As({_unitEnumName} unit) private void GenerateToString() { - Writer.WL($@" + Writer.WL(@" #region ToString Methods /// @@ -680,9 +679,9 @@ private void GenerateToString() /// /// String representation. public override string ToString() - {{ + { return ToString(null); - }} + } /// /// Get string representation of value and unit. Using two significant digits after radix. @@ -690,10 +689,10 @@ public override string ToString() /// String representation. /// Name of culture (ex: ""en-US"") to use for localization and number formatting. Defaults to if null. public string ToString([CanBeNull] string cultureName) - {{ + { var provider = cultureName; return ToString(provider, 2); - }} + } /// /// Get string representation of value and unit. @@ -702,22 +701,22 @@ public string ToString([CanBeNull] string cultureName) /// String representation. /// Name of culture (ex: ""en-US"") to use for localization and number formatting. Defaults to if null. public string ToString(string cultureName, int significantDigitsAfterRadix) - {{ + { var provider = cultureName; var value = Convert.ToDouble(Value); var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); return ToString(provider, format); - }} + } /// /// Get string representation of value and unit. /// - /// String format to use. Default: ""{{0:0.##}} {{1}} for value and unit abbreviation respectively."" + /// String format to use. Default: ""{0:0.##} {1} for value and unit abbreviation respectively."" /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. /// String representation. /// Name of culture (ex: ""en-US"") to use for localization and number formatting. Defaults to if null. public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - {{ + { var provider = GetFormatProviderFromCultureName(cultureName); if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); @@ -727,21 +726,21 @@ public string ToString([CanBeNull] string cultureName, [NotNull] string format, var value = Convert.ToDouble(Value); var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); - }} + } #endregion "); } - /// + /// internal static string GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText); - /// + /// internal static string GetObsoleteAttributeOrNull(Unit unit) => GetObsoleteAttributeOrNull(unit.ObsoleteText); /// - /// Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string - /// It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats + /// Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string + /// It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats /// private static string GetObsoleteAttributeOrNull(string obsoleteText) => string.IsNullOrWhiteSpace(obsoleteText) ? null diff --git a/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs index 582b299d6a..8b7d07bbca 100644 --- a/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs +++ b/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using CodeGen.JsonTypes; namespace CodeGen.Generators.UnitsNetWrcGen @@ -28,8 +31,11 @@ public enum QuantityType { Undefined = 0,"); foreach (var quantity in _quantities) + { Writer.WL($@" {quantity.Name},"); + } + Writer.WL(@" } }"); diff --git a/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs index 133a34850b..b8466156f1 100644 --- a/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using CodeGen.Helpers; using CodeGen.JsonTypes; @@ -51,14 +54,14 @@ internal static bool TryFrom(double value, Enum unit, out IQuantity quantity) return true;"); } - Writer.WL($@" + Writer.WL(@" default: - {{ + { quantity = default(IQuantity); return false; - }} - }} - }} + } + } + } /// internal static IQuantity Parse(Type quantityType, string quantityString) => Parse(null, quantityType, quantityString); @@ -72,14 +75,14 @@ internal static bool TryFrom(double value, Enum unit, out IQuantity quantity) /// The parsed quantity. /// Type must be of type UnitsNet.IQuantity -or- Type is not a known quantity type. internal static IQuantity Parse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString) - {{ + { if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) - throw new ArgumentException($""Type {{quantityType}} must be of type UnitsNet.IQuantity.""); + throw new ArgumentException($""Type {quantityType} must be of type UnitsNet.IQuantity.""); if (TryParse(formatProvider, quantityType, quantityString, out IQuantity quantity)) return quantity; - throw new ArgumentException($""Quantity string could not be parsed to quantity {{quantityType}}.""); - }} + throw new ArgumentException($""Quantity string could not be parsed to quantity {quantityType}.""); + } /// internal static bool TryParse(Type quantityType, string quantityString, out IQuantity quantity) => @@ -94,7 +97,7 @@ internal static bool TryParse(Type quantityType, string quantityString, out IQua /// The resulting quantity if successful, otherwise default. /// The parsed quantity. internal static bool TryParse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString, out IQuantity quantity) - {{ + { quantity = default(IQuantity); if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) @@ -110,12 +113,12 @@ internal static bool TryParse([CanBeNull] IFormatProvider formatProvider, Type q "); } - Writer.WL($@" + Writer.WL(@" throw new ArgumentException( - $""Type {{quantityType}} is not a known quantity type. Did you pass in a third-party quantity type defined outside UnitsNet library?""); - }} - }} -}}"); + $""Type {quantityType} is not a known quantity type. Did you pass in a third-party quantity type defined outside UnitsNet library?""); + } + } +}"); return Writer.ToString(); } } diff --git a/CodeGen/Generators/UnitsNetWrcGen/UnitAbbreviationsCacheGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/UnitAbbreviationsCacheGenerator.cs index 5695ad777a..3721be1359 100644 --- a/CodeGen/Generators/UnitsNetWrcGen/UnitAbbreviationsCacheGenerator.cs +++ b/CodeGen/Generators/UnitsNetWrcGen/UnitAbbreviationsCacheGenerator.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using System.Linq; using CodeGen.JsonTypes; diff --git a/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs index 939d947a17..e95c822c0e 100644 --- a/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs +++ b/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using CodeGen.Helpers; using CodeGen.JsonTypes; @@ -50,11 +53,11 @@ public enum {_unitEnumName} {unit.SingularName},"); } - Writer.WL($@" - }} + Writer.WL(@" + } #pragma warning restore 1591 -}}"); +}"); return Writer.ToString(); } } diff --git a/CodeGen/Helpers/MyTextWriter.cs b/CodeGen/Helpers/MyTextWriter.cs index 3fae829a09..b89940c3be 100644 --- a/CodeGen/Helpers/MyTextWriter.cs +++ b/CodeGen/Helpers/MyTextWriter.cs @@ -36,7 +36,8 @@ private string GetIndent(int indentLevel) } /// - /// Write line with current indent. Trims preceding newline if any, to simplify code formatting when calling this method. + /// Write line with current indent. Trims preceding newline if any, to simplify code formatting when calling this + /// method. /// /// The indent level to prepend the text with. /// The text to write @@ -47,7 +48,8 @@ public void WL(int indentLevel, string text = "") } /// - /// Write line with current indent. Trims preceding newline if any, to simplify code formatting when calling this method. + /// Write line with current indent. Trims preceding newline if any, to simplify code formatting when calling this + /// method. /// /// The text to write public void WL(string text = "") @@ -57,7 +59,8 @@ public void WL(string text = "") } /// - /// Write with current indent, but no newline. Trims preceding newline if any, to simplify code formatting when calling this method. + /// Write with current indent, but no newline. Trims preceding newline if any, to simplify code formatting when calling + /// this method. /// /// The text to write public void W(string text = "") @@ -85,7 +88,7 @@ public override string ToString() } /// - /// Write line with current ident only if actually contains text and not just whitespace. + /// Write line with current ident only if actually contains text and not just whitespace. /// /// The level of indentation to prepend to the text. /// The text to write. @@ -96,14 +99,16 @@ public void WLIfText(int indentLevel, string text) } /// - /// Write line with current ident only if is true. + /// Write line with current ident only if is true. /// /// The condition. /// The text to write. public void WLCondition(bool condition, string text) { if (condition) + { WL(text); + } } } } diff --git a/CodeGen/Helpers/StringExtensions.cs b/CodeGen/Helpers/StringExtensions.cs index 9091491889..70c0cbaef4 100644 --- a/CodeGen/Helpers/StringExtensions.cs +++ b/CodeGen/Helpers/StringExtensions.cs @@ -6,12 +6,12 @@ namespace CodeGen.Helpers internal static class StringExtensions { /// - /// Returns true if string is not null and not whitespace. + /// Returns true if string is not null and not whitespace. /// public static bool HasText(this string str) => !string.IsNullOrWhiteSpace(str); /// - /// Example: "Kilo" + ToCamelCase("NewtonPerMeter") => "KilonewtonPerMeter" + /// Example: "Kilo" + ToCamelCase("NewtonPerMeter") => "KilonewtonPerMeter" /// public static string ToCamelCase(this string str) { diff --git a/CodeGen/JsonTypes/BaseDimensions.cs b/CodeGen/JsonTypes/BaseDimensions.cs index a6caad21fd..87cada0970 100644 --- a/CodeGen/JsonTypes/BaseDimensions.cs +++ b/CodeGen/JsonTypes/BaseDimensions.cs @@ -10,16 +10,22 @@ internal class BaseDimensions /// AmountOfSubstance. public int N = 0; + /// ElectricCurrent. public int I = 0; + /// Length. public int L = 0; + /// LuminousIntensity. public int J = 0; + /// Mass. public int M = 0; + /// Temperature. public int Θ = 0; + /// Time. public int T = 0; diff --git a/CodeGen/JsonTypes/BaseUnits.cs b/CodeGen/JsonTypes/BaseUnits.cs index 46f0887811..e62aedc5b0 100644 --- a/CodeGen/JsonTypes/BaseUnits.cs +++ b/CodeGen/JsonTypes/BaseUnits.cs @@ -10,16 +10,22 @@ internal class BaseUnits /// AmountOfSubstance. public string N; + /// ElectricCurrent. public string I; + /// Length. public string L; + /// LuminousIntensity. public string J; + /// Mass. public string M; + /// Temperature. public string Θ; + /// Time. public string T; diff --git a/CodeGen/JsonTypes/Prefix.cs b/CodeGen/JsonTypes/Prefix.cs index 62d106bb39..a4ae586cce 100644 --- a/CodeGen/JsonTypes/Prefix.cs +++ b/CodeGen/JsonTypes/Prefix.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + namespace CodeGen.JsonTypes { internal enum Prefix @@ -32,4 +35,4 @@ internal enum Prefix Pebi, Exbi } -} \ No newline at end of file +} diff --git a/CodeGen/JsonTypes/Quantity.cs b/CodeGen/JsonTypes/Quantity.cs index 0888bf8464..4f2a91158a 100644 --- a/CodeGen/JsonTypes/Quantity.cs +++ b/CodeGen/JsonTypes/Quantity.cs @@ -2,7 +2,6 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using System.Collections.Generic; namespace CodeGen.JsonTypes { diff --git a/CodeGen/PrefixInfo.cs b/CodeGen/PrefixInfo.cs index 73d62c9517..ab6c4ba796 100644 --- a/CodeGen/PrefixInfo.cs +++ b/CodeGen/PrefixInfo.cs @@ -1,3 +1,6 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using System; using System.Collections.Generic; using System.Linq; @@ -18,32 +21,20 @@ internal class PrefixInfo // when creating decimal conversion functions in CodeGen.Generator.FixConversionFunctionsForDecimalValueTypes. // SI prefixes - new PrefixInfo(Prefix.Yocto, "1e-24d", "y"), - new PrefixInfo(Prefix.Zepto, "1e-21d", "z"), - new PrefixInfo(Prefix.Atto, "1e-18d", "a", (Russian, "а")), - new PrefixInfo(Prefix.Femto, "1e-15d", "f", (Russian, "ф")), - new PrefixInfo(Prefix.Pico, "1e-12d", "p", (Russian, "п")), - new PrefixInfo(Prefix.Nano, "1e-9d", "n", (Russian, "н")), - new PrefixInfo(Prefix.Micro, "1e-6d", "µ", (Russian, "мк")), - new PrefixInfo(Prefix.Milli, "1e-3d", "m", (Russian, "м")), - new PrefixInfo(Prefix.Centi, "1e-2d", "c", (Russian, "с")), - new PrefixInfo(Prefix.Deci, "1e-1d", "d", (Russian, "д")), - new PrefixInfo(Prefix.Deca, "1e1d", "da", (Russian, "да")), - new PrefixInfo(Prefix.Hecto, "1e2d", "h", (Russian, "г")), - new PrefixInfo(Prefix.Kilo, "1e3d", "k", (Russian, "к")), - new PrefixInfo(Prefix.Mega, "1e6d", "M", (Russian, "М")), - new PrefixInfo(Prefix.Giga, "1e9d", "G", (Russian, "Г")), - new PrefixInfo(Prefix.Tera, "1e12d", "T", (Russian, "Т")), - new PrefixInfo(Prefix.Peta, "1e15d", "P", (Russian, "П")), - new PrefixInfo(Prefix.Exa, "1e18d", "E", (Russian, "Э")), - new PrefixInfo(Prefix.Zetta, "1e21d", "Z"), - new PrefixInfo(Prefix.Yotta, "1e24d", "Y"), + new PrefixInfo(Prefix.Yocto, "1e-24d", "y"), new PrefixInfo(Prefix.Zepto, "1e-21d", "z"), + new PrefixInfo(Prefix.Atto, "1e-18d", "a", (Russian, "а")), new PrefixInfo(Prefix.Femto, "1e-15d", "f", (Russian, "ф")), + new PrefixInfo(Prefix.Pico, "1e-12d", "p", (Russian, "п")), new PrefixInfo(Prefix.Nano, "1e-9d", "n", (Russian, "н")), + new PrefixInfo(Prefix.Micro, "1e-6d", "µ", (Russian, "мк")), new PrefixInfo(Prefix.Milli, "1e-3d", "m", (Russian, "м")), + new PrefixInfo(Prefix.Centi, "1e-2d", "c", (Russian, "с")), new PrefixInfo(Prefix.Deci, "1e-1d", "d", (Russian, "д")), + new PrefixInfo(Prefix.Deca, "1e1d", "da", (Russian, "да")), new PrefixInfo(Prefix.Hecto, "1e2d", "h", (Russian, "г")), + new PrefixInfo(Prefix.Kilo, "1e3d", "k", (Russian, "к")), new PrefixInfo(Prefix.Mega, "1e6d", "M", (Russian, "М")), + new PrefixInfo(Prefix.Giga, "1e9d", "G", (Russian, "Г")), new PrefixInfo(Prefix.Tera, "1e12d", "T", (Russian, "Т")), + new PrefixInfo(Prefix.Peta, "1e15d", "P", (Russian, "П")), new PrefixInfo(Prefix.Exa, "1e18d", "E", (Russian, "Э")), + new PrefixInfo(Prefix.Zetta, "1e21d", "Z"), new PrefixInfo(Prefix.Yotta, "1e24d", "Y"), // Binary prefixes - new PrefixInfo(Prefix.Kibi, "1024d", "Ki"), - new PrefixInfo(Prefix.Mebi, "(1024d * 1024)", "Mi"), - new PrefixInfo(Prefix.Gibi, "(1024d * 1024 * 1024)", "Gi"), - new PrefixInfo(Prefix.Tebi, "(1024d * 1024 * 1024 * 1024)", "Ti"), + new PrefixInfo(Prefix.Kibi, "1024d", "Ki"), new PrefixInfo(Prefix.Mebi, "(1024d * 1024)", "Mi"), + new PrefixInfo(Prefix.Gibi, "(1024d * 1024 * 1024)", "Gi"), new PrefixInfo(Prefix.Tebi, "(1024d * 1024 * 1024 * 1024)", "Ti"), new PrefixInfo(Prefix.Pebi, "(1024d * 1024 * 1024 * 1024 * 1024)", "Pi"), new PrefixInfo(Prefix.Exbi, "(1024d * 1024 * 1024 * 1024 * 1024 * 1024)", "Ei") }.ToDictionary(prefixInfo => prefixInfo.Prefix); diff --git a/CodeGen/Program.cs b/CodeGen/Program.cs index c930b4bd1d..e26fe9655a 100644 --- a/CodeGen/Program.cs +++ b/CodeGen/Program.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using System.Diagnostics; using System.IO; using System.Linq; @@ -65,7 +68,9 @@ private static int Main(bool verbose = false, DirectoryInfo repositoryRoot = nul UnitsNetGenerator.Generate(rootDir, quantities); if (!skipWrc) + { UnitsNetWrcGenerator.Generate(rootDir, quantities); + } Log.Information($"Completed in {sw.ElapsedMilliseconds} ms!", ConsoleColor.Green); return 0; diff --git a/Common/UnitDefinitions/Acceleration.json b/Common/UnitDefinitions/Acceleration.json index ed292ace3c..3eb336c3e4 100644 --- a/Common/UnitDefinitions/Acceleration.json +++ b/Common/UnitDefinitions/Acceleration.json @@ -1,7 +1,8 @@ { "Name": "Acceleration", "BaseUnit": "MeterPerSecondSquared", - "XmlDoc": "Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration.", + "XmlDoc": + "Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration.", "BaseDimensions": { "L": 1, "T": -2 @@ -16,11 +17,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m/s²" ] + "Abbreviations": ["m/s²"] } ] }, @@ -36,7 +37,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "in/s²" ] + "Abbreviations": ["in/s²"] } ] }, @@ -52,7 +53,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft/s²" ] + "Abbreviations": ["ft/s²"] } ] }, @@ -68,7 +69,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kn/s" ] + "Abbreviations": ["kn/s"] } ] }, @@ -84,7 +85,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kn/min" ] + "Abbreviations": ["kn/min"] } ] }, @@ -100,7 +101,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kn/h" ] + "Abbreviations": ["kn/h"] } ] }, @@ -116,7 +117,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g" ] + "Abbreviations": ["g"] } ] } diff --git a/Common/UnitDefinitions/AmountOfSubstance.json b/Common/UnitDefinitions/AmountOfSubstance.json index 101b13dcde..3992bfea02 100644 --- a/Common/UnitDefinitions/AmountOfSubstance.json +++ b/Common/UnitDefinitions/AmountOfSubstance.json @@ -1,7 +1,8 @@ { "Name": "AmountOfSubstance", "BaseUnit": "Mole", - "XmlDoc": "Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals.", + "XmlDoc": + "Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals.", "BaseDimensions": { "N": 1 }, @@ -14,11 +15,11 @@ "BaseUnits": { "N": "Mole" }, - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega"], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mol" ] + "Abbreviations": ["mol"] } ] }, @@ -30,11 +31,11 @@ }, "FromUnitToBaseFunc": "x*453.59237", "FromBaseToUnitFunc": "x/453.59237", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbmol" ] + "Abbreviations": ["lbmol"] } ] } diff --git a/Common/UnitDefinitions/AmplitudeRatio.json b/Common/UnitDefinitions/AmplitudeRatio.json index b735680ad4..0a71dae003 100644 --- a/Common/UnitDefinitions/AmplitudeRatio.json +++ b/Common/UnitDefinitions/AmplitudeRatio.json @@ -13,7 +13,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dBV" ] + "Abbreviations": ["dBV"] } ] }, @@ -25,7 +25,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dBµV" ] + "Abbreviations": ["dBµV"] } ] }, @@ -37,7 +37,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dBmV" ] + "Abbreviations": ["dBmV"] } ] }, @@ -49,7 +49,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dBu" ] + "Abbreviations": ["dBu"] } ] } diff --git a/Common/UnitDefinitions/Angle.json b/Common/UnitDefinitions/Angle.json index e551955751..953df60aba 100644 --- a/Common/UnitDefinitions/Angle.json +++ b/Common/UnitDefinitions/Angle.json @@ -1,39 +1,40 @@ { "Name": "Angle", "BaseUnit": "Degree", - "XmlDoc": "In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle.", + "XmlDoc": + "In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle.", "Units": [ { "SingularName": "Radian", "PluralName": "Radians", "FromUnitToBaseFunc": "x*180/Math.PI", "FromBaseToUnitFunc": "x/180*Math.PI", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "rad" ] + "Abbreviations": ["rad"] }, { "Culture": "ru-RU", - "Abbreviations": [ "рад" ] + "Abbreviations": ["рад"] } ] }, { "SingularName": "Degree", "PluralName": "Degrees", - "Prefixes": [ "Nano", "Micro", "Milli" ], + "Prefixes": ["Nano", "Micro", "Milli"], "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°", "deg" ] + "Abbreviations": ["°", "deg"] }, { "Culture": "ru-RU", - "Abbreviations": [ "°" ] + "Abbreviations": ["°"] } ] }, @@ -45,7 +46,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "'", "arcmin", "amin", "min" ] + "Abbreviations": ["'", "arcmin", "amin", "min"] } ] }, @@ -57,7 +58,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "″", "arcsec", "asec", "sec" ] + "Abbreviations": ["″", "arcsec", "asec", "sec"] } ] }, @@ -69,11 +70,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g" ] + "Abbreviations": ["g"] }, { "Culture": "ru-RU", - "Abbreviations": [ "g" ] + "Abbreviations": ["g"] } ] }, @@ -85,11 +86,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "r" ] + "Abbreviations": ["r"] }, { "Culture": "ru-RU", - "Abbreviations": [ "r" ] + "Abbreviations": ["r"] } ] } diff --git a/Common/UnitDefinitions/ApparentEnergy.json b/Common/UnitDefinitions/ApparentEnergy.json index 9f59768dd2..ccd57d1e54 100644 --- a/Common/UnitDefinitions/ApparentEnergy.json +++ b/Common/UnitDefinitions/ApparentEnergy.json @@ -1,7 +1,8 @@ { "Name": "ApparentEnergy", "BaseUnit": "VoltampereHour", - "XmlDoc": "A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules.", + "XmlDoc": + "A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules.", "BaseDimensions": { "L": 2, "M": 1, @@ -13,11 +14,11 @@ "PluralName": "VoltampereHours", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "VAh" ] + "Abbreviations": ["VAh"] } ] } diff --git a/Common/UnitDefinitions/ApparentPower.json b/Common/UnitDefinitions/ApparentPower.json index 83312e8d8e..f46f980550 100644 --- a/Common/UnitDefinitions/ApparentPower.json +++ b/Common/UnitDefinitions/ApparentPower.json @@ -1,7 +1,8 @@ { "Name": "ApparentPower", "BaseUnit": "Voltampere", - "XmlDoc": "Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current.", + "XmlDoc": + "Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current.", "BaseDimensions": { "L": 2, "M": 1, @@ -13,11 +14,11 @@ "PluralName": "Voltamperes", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega", "Giga" ], + "Prefixes": ["Kilo", "Mega", "Giga"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "VA" ] + "Abbreviations": ["VA"] } ] } diff --git a/Common/UnitDefinitions/Area.json b/Common/UnitDefinitions/Area.json index 07d52dfd56..b4cb808250 100644 --- a/Common/UnitDefinitions/Area.json +++ b/Common/UnitDefinitions/Area.json @@ -1,7 +1,8 @@ { "Name": "Area", "BaseUnit": "SquareMeter", - "XmlDoc": "Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept).", + "XmlDoc": + "Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept).", "BaseDimensions": { "L": 2 }, @@ -17,11 +18,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "km²" ] + "Abbreviations": ["km²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "км²" ] + "Abbreviations": ["км²"] } ] }, @@ -36,11 +37,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m²" ] + "Abbreviations": ["m²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "м²" ] + "Abbreviations": ["м²"] } ] }, @@ -55,11 +56,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dm²" ] + "Abbreviations": ["dm²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "дм²" ] + "Abbreviations": ["дм²"] } ] }, @@ -74,11 +75,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cm²" ] + "Abbreviations": ["cm²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "см²" ] + "Abbreviations": ["см²"] } ] }, @@ -93,11 +94,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mm²" ] + "Abbreviations": ["mm²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "мм²" ] + "Abbreviations": ["мм²"] } ] }, @@ -112,11 +113,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "µm²" ] + "Abbreviations": ["µm²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "мкм²" ] + "Abbreviations": ["мкм²"] } ] }, @@ -131,11 +132,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mi²" ] + "Abbreviations": ["mi²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "миля²" ] + "Abbreviations": ["миля²"] } ] }, @@ -150,11 +151,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "yd²" ] + "Abbreviations": ["yd²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "ярд²" ] + "Abbreviations": ["ярд²"] } ] }, @@ -169,11 +170,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft²" ] + "Abbreviations": ["ft²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "фут²" ] + "Abbreviations": ["фут²"] } ] }, @@ -188,7 +189,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft² (US)" ] + "Abbreviations": ["ft² (US)"] } ] }, @@ -203,11 +204,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "in²" ] + "Abbreviations": ["in²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "дюйм²" ] + "Abbreviations": ["дюйм²"] } ] }, @@ -219,7 +220,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ac" ] + "Abbreviations": ["ac"] } ] }, @@ -231,7 +232,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ha" ] + "Abbreviations": ["ha"] } ] }, @@ -248,4 +249,4 @@ ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/AreaDensity.json b/Common/UnitDefinitions/AreaDensity.json index 2b3623d107..bf051fcb26 100644 --- a/Common/UnitDefinitions/AreaDensity.json +++ b/Common/UnitDefinitions/AreaDensity.json @@ -19,7 +19,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kg/m²" ] + "Abbreviations": ["kg/m²"] } ] } diff --git a/Common/UnitDefinitions/AreaMomentOfInertia.json b/Common/UnitDefinitions/AreaMomentOfInertia.json index 0e288f8994..5fbe4e265c 100644 --- a/Common/UnitDefinitions/AreaMomentOfInertia.json +++ b/Common/UnitDefinitions/AreaMomentOfInertia.json @@ -17,7 +17,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m⁴", "m^4" ] + "Abbreviations": ["m⁴", "m^4"] } ] }, @@ -32,7 +32,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dm⁴", "dm^4" ] + "Abbreviations": ["dm⁴", "dm^4"] } ] }, @@ -47,7 +47,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cm⁴", "cm^4" ] + "Abbreviations": ["cm⁴", "cm^4"] } ] }, @@ -62,7 +62,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mm⁴", "mm^4" ] + "Abbreviations": ["mm⁴", "mm^4"] } ] }, @@ -77,7 +77,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft⁴", "ft^4" ] + "Abbreviations": ["ft⁴", "ft^4"] } ] }, @@ -92,7 +92,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "in⁴", "in^4" ] + "Abbreviations": ["in⁴", "in^4"] } ] } diff --git a/Common/UnitDefinitions/BitRate.json b/Common/UnitDefinitions/BitRate.json index b768a1c9e5..1385d33d8b 100644 --- a/Common/UnitDefinitions/BitRate.json +++ b/Common/UnitDefinitions/BitRate.json @@ -2,7 +2,8 @@ "Name": "BitRate", "BaseUnit": "BitPerSecond", "BaseType": "decimal", - "XmlDoc": "In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time.", + "XmlDoc": + "In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Bit_rate", "Units": [ { @@ -10,11 +11,11 @@ "PluralName": "BitsPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi" ], + "Prefixes": ["Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bit/s", "bps" ] + "Abbreviations": ["bit/s", "bps"] } ] }, @@ -23,11 +24,11 @@ "PluralName": "BytesPerSecond", "FromUnitToBaseFunc": "x*8m", "FromBaseToUnitFunc": "x/8m", - "Prefixes": [ "Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi" ], + "Prefixes": ["Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "B/s" ] + "Abbreviations": ["B/s"] } ] } diff --git a/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json b/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json index 34b30675d7..e6ac382c2f 100644 --- a/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json +++ b/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json @@ -1,7 +1,8 @@ { "Name": "BrakeSpecificFuelConsumption", "BaseUnit": "KilogramPerJoule", - "XmlDoc": "Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output.", + "XmlDoc": + "Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output.", "BaseDimensions": { "L": -2, "T": 2 @@ -15,7 +16,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/kWh" ] + "Abbreviations": ["g/kWh"] } ] }, @@ -27,7 +28,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kg/J" ] + "Abbreviations": ["kg/J"] } ] }, @@ -40,7 +41,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/hph" ] + "Abbreviations": ["lb/hph"] } ] } diff --git a/Common/UnitDefinitions/Capacitance.json b/Common/UnitDefinitions/Capacitance.json index 5d992e9230..70005c3b8d 100644 --- a/Common/UnitDefinitions/Capacitance.json +++ b/Common/UnitDefinitions/Capacitance.json @@ -21,11 +21,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Kilo", "Mega" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "F" ] + "Abbreviations": ["F"] } ] } diff --git a/Common/UnitDefinitions/CoefficientOfThermalExpansion.json b/Common/UnitDefinitions/CoefficientOfThermalExpansion.json index 793d9363ae..cc4ec14723 100644 --- a/Common/UnitDefinitions/CoefficientOfThermalExpansion.json +++ b/Common/UnitDefinitions/CoefficientOfThermalExpansion.json @@ -17,7 +17,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "K⁻¹", "1/K" ] + "Abbreviations": ["K⁻¹", "1/K"] } ] }, @@ -32,7 +32,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°C⁻¹", "1/°C" ] + "Abbreviations": ["°C⁻¹", "1/°C"] } ] }, @@ -47,7 +47,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°F⁻¹", "1/°F" ] + "Abbreviations": ["°F⁻¹", "1/°F"] } ] } diff --git a/Common/UnitDefinitions/Density.json b/Common/UnitDefinitions/Density.json index 0849bec96a..b99292169c 100644 --- a/Common/UnitDefinitions/Density.json +++ b/Common/UnitDefinitions/Density.json @@ -17,11 +17,11 @@ }, "FromUnitToBaseFunc": "x/1e-6", "FromBaseToUnitFunc": "x*1e-6", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/mm³" ] + "Abbreviations": ["g/mm³"] } ] }, @@ -34,11 +34,11 @@ }, "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/cm³" ] + "Abbreviations": ["g/cm³"] } ] }, @@ -51,15 +51,15 @@ }, "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": [ "Kilo", "Milli", "Micro" ], + "Prefixes": ["Kilo", "Milli", "Micro"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/m³" ] + "Abbreviations": ["g/m³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "г/м³" ] + "Abbreviations": ["г/м³"] } ] }, @@ -72,11 +72,11 @@ }, "FromUnitToBaseFunc": "x/3.6127298147753e-5", "FromBaseToUnitFunc": "x*3.6127298147753e-5", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/in³" ], + "Abbreviations": ["lb/in³"], "AbbreviationsForPrefixes": { "Kilo": "kip/in³" } } ] @@ -90,11 +90,11 @@ }, "FromUnitToBaseFunc": "x/0.062427961", "FromBaseToUnitFunc": "x*0.062427961", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/ft³" ], + "Abbreviations": ["lb/ft³"], "AbbreviationsForPrefixes": { "Kilo": "kip/ft³" } } ] @@ -111,7 +111,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t/mm³" ] + "Abbreviations": ["t/mm³"] } ] }, @@ -127,7 +127,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t/cm³" ] + "Abbreviations": ["t/cm³"] } ] }, @@ -143,7 +143,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t/m³" ] + "Abbreviations": ["t/m³"] } ] }, @@ -159,7 +159,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "slug/ft³" ] + "Abbreviations": ["slug/ft³"] } ] }, @@ -168,11 +168,11 @@ "PluralName": "GramsPerLiter", "FromUnitToBaseFunc": "x/1", "FromBaseToUnitFunc": "x*1", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/L" ] + "Abbreviations": ["g/L"] } ] }, @@ -181,11 +181,11 @@ "PluralName": "GramsPerDeciLiter", "FromUnitToBaseFunc": "x/1e-1", "FromBaseToUnitFunc": "x*1e-1", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/dl" ] + "Abbreviations": ["g/dl"] } ] }, @@ -194,11 +194,11 @@ "PluralName": "GramsPerMilliliter", "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/ml" ] + "Abbreviations": ["g/ml"] } ] }, @@ -210,7 +210,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppg (U.S.)" ] + "Abbreviations": ["ppg (U.S.)"] } ] }, @@ -222,7 +222,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppg (imp.)" ] + "Abbreviations": ["ppg (imp.)"] } ] }, @@ -238,9 +238,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kg/l" ] + "Abbreviations": ["kg/l"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/Duration.json b/Common/UnitDefinitions/Duration.json index 9edffaeae3..f821ccae98 100644 --- a/Common/UnitDefinitions/Duration.json +++ b/Common/UnitDefinitions/Duration.json @@ -1,7 +1,8 @@ { "Name": "Duration", "BaseUnit": "Second", - "XmlDoc": "Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them.", + "XmlDoc": + "Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them.", "BaseDimensions": { "T": 1 }, @@ -17,11 +18,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "yr", "year", "years" ] + "Abbreviations": ["yr", "year", "years"] }, { "Culture": "ru-RU", - "Abbreviations": [ "год" ] + "Abbreviations": ["год"] } ] }, @@ -36,11 +37,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mo", "month", "months" ] + "Abbreviations": ["mo", "month", "months"] }, { "Culture": "ru-RU", - "Abbreviations": [ "месяц" ] + "Abbreviations": ["месяц"] } ] }, @@ -55,11 +56,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "wk", "week", "weeks" ] + "Abbreviations": ["wk", "week", "weeks"] }, { "Culture": "ru-RU", - "Abbreviations": [ "мин" ] + "Abbreviations": ["мин"] } ] }, @@ -74,11 +75,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "d", "day", "days" ] + "Abbreviations": ["d", "day", "days"] }, { "Culture": "ru-RU", - "Abbreviations": [ "д" ] + "Abbreviations": ["д"] } ] }, @@ -93,11 +94,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "h", "hr", "hrs", "hour", "hours" ] + "Abbreviations": ["h", "hr", "hrs", "hour", "hours"] }, { "Culture": "ru-RU", - "Abbreviations": [ "ч" ] + "Abbreviations": ["ч"] } ] }, @@ -112,11 +113,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m", "min", "minute", "minutes" ] + "Abbreviations": ["m", "min", "minute", "minutes"] }, { "Culture": "ru-RU", - "Abbreviations": [ "мин" ] + "Abbreviations": ["мин"] } ] }, @@ -128,17 +129,17 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli" ], + "Prefixes": ["Nano", "Micro", "Milli"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "s", "sec", "secs", "second", "seconds" ] + "Abbreviations": ["s", "sec", "secs", "second", "seconds"] }, { "Culture": "ru-RU", - "Abbreviations": [ "с", "сек" ] + "Abbreviations": ["с", "сек"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/DynamicViscosity.json b/Common/UnitDefinitions/DynamicViscosity.json index 8770ba982b..54103be9c0 100644 --- a/Common/UnitDefinitions/DynamicViscosity.json +++ b/Common/UnitDefinitions/DynamicViscosity.json @@ -1,7 +1,8 @@ { "Name": "DynamicViscosity", "BaseUnit": "NewtonSecondPerMeterSquared", - "XmlDoc": "The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds", + "XmlDoc": + "The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity", "BaseDimensions": { "L": -1, @@ -17,7 +18,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Ns/m²" ] + "Abbreviations": ["Ns/m²"] } ] }, @@ -26,11 +27,11 @@ "PluralName": "PascalSeconds", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Milli", "Micro" ], + "Prefixes": ["Milli", "Micro"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Pa·s", "PaS" ] + "Abbreviations": ["Pa·s", "PaS"] } ] }, @@ -39,11 +40,11 @@ "PluralName": "Poise", "FromUnitToBaseFunc": "x/10", "FromBaseToUnitFunc": "x*10", - "Prefixes": [ "Centi" ], + "Prefixes": ["Centi"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "P" ] + "Abbreviations": ["P"] } ] }, @@ -55,7 +56,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "reyn" ] + "Abbreviations": ["reyn"] } ] }, @@ -67,7 +68,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf·s/in²" ] + "Abbreviations": ["lbf·s/in²"] } ] }, @@ -79,7 +80,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf·s/ft²" ] + "Abbreviations": ["lbf·s/ft²"] } ] } diff --git a/Common/UnitDefinitions/ElectricAdmittance.json b/Common/UnitDefinitions/ElectricAdmittance.json index 03b5b9b9a2..65799a269f 100644 --- a/Common/UnitDefinitions/ElectricAdmittance.json +++ b/Common/UnitDefinitions/ElectricAdmittance.json @@ -1,7 +1,8 @@ { "Name": "ElectricAdmittance", "BaseUnit": "Siemens", - "XmlDoc": "Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S).", + "XmlDoc": + "Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S).", "BaseDimensions": { "L": -2, "M": -1, @@ -14,11 +15,11 @@ "PluralName": "Siemens", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli" ], + "Prefixes": ["Nano", "Micro", "Milli"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "S" ] + "Abbreviations": ["S"] } ] } diff --git a/Common/UnitDefinitions/ElectricCharge.json b/Common/UnitDefinitions/ElectricCharge.json index 36e28fc9ff..51c25f2abe 100644 --- a/Common/UnitDefinitions/ElectricCharge.json +++ b/Common/UnitDefinitions/ElectricCharge.json @@ -1,7 +1,8 @@ { "Name": "ElectricCharge", "BaseUnit": "Coulomb", - "XmlDoc": "Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field.", + "XmlDoc": + "Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electric_charge", "BaseDimensions": { "T": 1, @@ -16,7 +17,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "C" ] + "Abbreviations": ["C"] } ] }, @@ -25,11 +26,11 @@ "PluralName": "AmpereHours", "FromUnitToBaseFunc": "x/2.77777777777e-4", "FromBaseToUnitFunc": "x*2.77777777777e-4", - "Prefixes": [ "Milli", "Kilo", "Mega" ], + "Prefixes": ["Milli", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "A-h", "Ah" ] + "Abbreviations": ["A-h", "Ah"] } ] } diff --git a/Common/UnitDefinitions/ElectricChargeDensity.json b/Common/UnitDefinitions/ElectricChargeDensity.json index 3282494a74..264148a10c 100644 --- a/Common/UnitDefinitions/ElectricChargeDensity.json +++ b/Common/UnitDefinitions/ElectricChargeDensity.json @@ -22,7 +22,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "C/m³" ] + "Abbreviations": ["C/m³"] } ] } diff --git a/Common/UnitDefinitions/ElectricConductance.json b/Common/UnitDefinitions/ElectricConductance.json index 52f48b373a..96252c9197 100644 --- a/Common/UnitDefinitions/ElectricConductance.json +++ b/Common/UnitDefinitions/ElectricConductance.json @@ -1,7 +1,8 @@ { "Name": "ElectricConductance", "BaseUnit": "Siemens", - "XmlDoc": "The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor.", + "XmlDoc": + "The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance", "BaseDimensions": { "L": -2, @@ -15,11 +16,11 @@ "PluralName": "Siemens", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Milli", "Micro" ], + "Prefixes": ["Milli", "Micro"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "S" ] + "Abbreviations": ["S"] } ] } diff --git a/Common/UnitDefinitions/ElectricConductivity.json b/Common/UnitDefinitions/ElectricConductivity.json index 77d38bd48e..3133a95017 100644 --- a/Common/UnitDefinitions/ElectricConductivity.json +++ b/Common/UnitDefinitions/ElectricConductivity.json @@ -1,7 +1,8 @@ { "Name": "ElectricConductivity", "BaseUnit": "SiemensPerMeter", - "XmlDoc": "Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current.", + "XmlDoc": + "Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity", "BaseDimensions": { "L": -3, @@ -24,7 +25,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "S/m" ] + "Abbreviations": ["S/m"] } ] }, @@ -36,7 +37,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "S/in" ] + "Abbreviations": ["S/in"] } ] }, @@ -48,7 +49,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "S/ft" ] + "Abbreviations": ["S/ft"] } ] } diff --git a/Common/UnitDefinitions/ElectricCurrent.json b/Common/UnitDefinitions/ElectricCurrent.json index d3e9305926..051a5fc6ae 100644 --- a/Common/UnitDefinitions/ElectricCurrent.json +++ b/Common/UnitDefinitions/ElectricCurrent.json @@ -1,7 +1,8 @@ { "Name": "ElectricCurrent", "BaseUnit": "Ampere", - "XmlDoc": "An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma.", + "XmlDoc": + "An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma.", "BaseDimensions": { "I": 1 }, @@ -14,11 +15,11 @@ "BaseUnits": { "I": "Ampere" }, - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Kilo", "Mega" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "A" ] + "Abbreviations": ["A"] } ] } diff --git a/Common/UnitDefinitions/ElectricCurrentDensity.json b/Common/UnitDefinitions/ElectricCurrentDensity.json index dbbb57ac0f..6f4b7ff2d9 100644 --- a/Common/UnitDefinitions/ElectricCurrentDensity.json +++ b/Common/UnitDefinitions/ElectricCurrentDensity.json @@ -20,7 +20,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "A/m²" ] + "Abbreviations": ["A/m²"] } ] }, @@ -36,7 +36,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "A/in²" ] + "Abbreviations": ["A/in²"] } ] }, @@ -52,7 +52,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "A/ft²" ] + "Abbreviations": ["A/ft²"] } ] } diff --git a/Common/UnitDefinitions/ElectricCurrentGradient.json b/Common/UnitDefinitions/ElectricCurrentGradient.json index 188fffda98..cc4f87aeb2 100644 --- a/Common/UnitDefinitions/ElectricCurrentGradient.json +++ b/Common/UnitDefinitions/ElectricCurrentGradient.json @@ -15,7 +15,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "A/s" ] + "Abbreviations": ["A/s"] } ] } diff --git a/Common/UnitDefinitions/ElectricField.json b/Common/UnitDefinitions/ElectricField.json index 3a806fd98b..1014a1b1c7 100644 --- a/Common/UnitDefinitions/ElectricField.json +++ b/Common/UnitDefinitions/ElectricField.json @@ -1,7 +1,8 @@ { "Name": "ElectricField", "BaseUnit": "VoltPerMeter", - "XmlDoc": "An electric field is a force field that surrounds electric charges that attracts or repels other electric charges.", + "XmlDoc": + "An electric field is a force field that surrounds electric charges that attracts or repels other electric charges.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electric_field", "BaseDimensions": { "L": 1, @@ -24,7 +25,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "V/m" ] + "Abbreviations": ["V/m"] } ] } diff --git a/Common/UnitDefinitions/ElectricInductance.json b/Common/UnitDefinitions/ElectricInductance.json index 90df93bead..a7c5a99b37 100644 --- a/Common/UnitDefinitions/ElectricInductance.json +++ b/Common/UnitDefinitions/ElectricInductance.json @@ -15,11 +15,11 @@ "PluralName": "Henries", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli" ], + "Prefixes": ["Nano", "Micro", "Milli"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "H" ] + "Abbreviations": ["H"] } ] } diff --git a/Common/UnitDefinitions/ElectricPotential.json b/Common/UnitDefinitions/ElectricPotential.json index b1177e4442..23d471b5b3 100644 --- a/Common/UnitDefinitions/ElectricPotential.json +++ b/Common/UnitDefinitions/ElectricPotential.json @@ -1,7 +1,8 @@ { "Name": "ElectricPotential", "BaseUnit": "Volt", - "XmlDoc": "In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point.", + "XmlDoc": + "In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point.", "BaseDimensions": { "L": 2, "M": 1, @@ -20,15 +21,15 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Micro", "Milli", "Kilo", "Mega" ], + "Prefixes": ["Micro", "Milli", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "V" ] + "Abbreviations": ["V"] }, { "Culture": "ru-RU", - "Abbreviations": [ "В" ] + "Abbreviations": ["В"] } ] } diff --git a/Common/UnitDefinitions/ElectricPotentialAc.json b/Common/UnitDefinitions/ElectricPotentialAc.json index d5835f95ed..e6cce8b6e1 100644 --- a/Common/UnitDefinitions/ElectricPotentialAc.json +++ b/Common/UnitDefinitions/ElectricPotentialAc.json @@ -8,11 +8,11 @@ "PluralName": "VoltsAc", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Micro", "Milli", "Kilo", "Mega" ], + "Prefixes": ["Micro", "Milli", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Vac" ] + "Abbreviations": ["Vac"] } ] } diff --git a/Common/UnitDefinitions/ElectricPotentialDc.json b/Common/UnitDefinitions/ElectricPotentialDc.json index 80c9f71e31..648026ed69 100644 --- a/Common/UnitDefinitions/ElectricPotentialDc.json +++ b/Common/UnitDefinitions/ElectricPotentialDc.json @@ -8,11 +8,11 @@ "PluralName": "VoltsDc", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Micro", "Milli", "Kilo", "Mega" ], + "Prefixes": ["Micro", "Milli", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Vdc" ] + "Abbreviations": ["Vdc"] } ] } diff --git a/Common/UnitDefinitions/ElectricResistance.json b/Common/UnitDefinitions/ElectricResistance.json index 247c810824..88fad97d1b 100644 --- a/Common/UnitDefinitions/ElectricResistance.json +++ b/Common/UnitDefinitions/ElectricResistance.json @@ -1,7 +1,8 @@ { "Name": "ElectricResistance", "BaseUnit": "Ohm", - "XmlDoc": "The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor.", + "XmlDoc": + "The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor.", "BaseDimensions": { "L": 2, "M": 1, @@ -14,11 +15,11 @@ "PluralName": "Ohms", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Milli", "Kilo", "Mega", "Giga"], + "Prefixes": ["Milli", "Kilo", "Mega", "Giga"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Ω" ] + "Abbreviations": ["Ω"] } ] } diff --git a/Common/UnitDefinitions/ElectricResistivity.json b/Common/UnitDefinitions/ElectricResistivity.json index 8ebbd8419f..3ad3db29af 100644 --- a/Common/UnitDefinitions/ElectricResistivity.json +++ b/Common/UnitDefinitions/ElectricResistivity.json @@ -1,7 +1,8 @@ { "Name": "ElectricResistivity", "BaseUnit": "OhmMeter", - "XmlDoc": "Electrical resistivity (also known as resistivity, specific electrical resistance, or volume resistivity) is a fundamental property that quantifies how strongly a given material opposes the flow of electric current.", + "XmlDoc": + "Electrical resistivity (also known as resistivity, specific electrical resistance, or volume resistivity) is a fundamental property that quantifies how strongly a given material opposes the flow of electric current.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity", "BaseDimensions": { "L": 3, @@ -15,11 +16,11 @@ "PluralName": "OhmMeters", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Kilo", "Mega" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Ω·m" ] + "Abbreviations": ["Ω·m"] } ] }, @@ -28,11 +29,11 @@ "PluralName": "OhmsCentimeter", "FromUnitToBaseFunc": "x/100", "FromBaseToUnitFunc": "x*100", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Kilo", "Mega" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Ω·cm" ] + "Abbreviations": ["Ω·cm"] } ] } diff --git a/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json b/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json index 3528f3c2cd..6816fc4dcd 100644 --- a/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json +++ b/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json @@ -1,7 +1,8 @@ { "Name": "ElectricSurfaceChargeDensity", "BaseUnit": "CoulombPerSquareMeter", - "XmlDoc": "In electromagnetism, surface charge density is a measure of the amount of electric charge per surface area.", + "XmlDoc": + "In electromagnetism, surface charge density is a measure of the amount of electric charge per surface area.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Charge_density", "BaseDimensions": { "L": -2, @@ -22,7 +23,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "C/m²" ] + "Abbreviations": ["C/m²"] } ] }, @@ -39,7 +40,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "C/cm²" ] + "Abbreviations": ["C/cm²"] } ] }, @@ -56,7 +57,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "C/in²" ] + "Abbreviations": ["C/in²"] } ] } diff --git a/Common/UnitDefinitions/Energy.json b/Common/UnitDefinitions/Energy.json index ec0b75e657..75547d0dcf 100644 --- a/Common/UnitDefinitions/Energy.json +++ b/Common/UnitDefinitions/Energy.json @@ -1,7 +1,8 @@ { "Name": "Energy", "BaseUnit": "Joule", - "XmlDoc": "The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used.", + "XmlDoc": + "The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used.", "BaseDimensions": { "L": 2, "M": 1, @@ -18,11 +19,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Milli", "Kilo", "Mega", "Giga" ], + "Prefixes": ["Milli", "Kilo", "Mega", "Giga"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J" ] + "Abbreviations": ["J"] } ] }, @@ -31,11 +32,11 @@ "PluralName": "Calories", "FromUnitToBaseFunc": "x*4.184", "FromBaseToUnitFunc": "x/4.184", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cal" ] + "Abbreviations": ["cal"] } ] }, @@ -44,11 +45,11 @@ "PluralName": "BritishThermalUnits", "FromUnitToBaseFunc": "x*1055.05585262", "FromBaseToUnitFunc": "x/1055.05585262", - "Prefixes": [ "Kilo", "Mega", "Giga" ], + "Prefixes": ["Kilo", "Mega", "Giga"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "BTU" ] + "Abbreviations": ["BTU"] } ] }, @@ -60,7 +61,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "eV" ] + "Abbreviations": ["eV"] } ] }, @@ -72,7 +73,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft·lb" ] + "Abbreviations": ["ft·lb"] } ] }, @@ -84,7 +85,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "erg" ] + "Abbreviations": ["erg"] } ] }, @@ -93,15 +94,15 @@ "PluralName": "WattHours", "FromUnitToBaseFunc": "x*3600d", "FromBaseToUnitFunc": "x/3600d", - "Prefixes": [ "Kilo", "Mega", "Giga", "Tera" ], + "Prefixes": ["Kilo", "Mega", "Giga", "Tera"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Wh" ] + "Abbreviations": ["Wh"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Вт/ч" ] + "Abbreviations": ["Вт/ч"] } ] }, @@ -110,16 +111,16 @@ "PluralName": "ThermsEc", "FromUnitToBaseFunc": "x*1.05505585262e8", "FromBaseToUnitFunc": "x/1.05505585262e8", - "Prefixes": [ "Deca" ], + "Prefixes": ["Deca"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "th (E.C.)" ], + "Abbreviations": ["th (E.C.)"], "AbbreviationsForPrefixes": { "Deca": "Dth (E.C.)" } }, { "Culture": "ru-RU", - "Abbreviations": [ "Европейский терм" ], + "Abbreviations": ["Европейский терм"], "AbbreviationsForPrefixes": { "Deca": "Европейский декатерм" } } ] @@ -129,16 +130,16 @@ "PluralName": "ThermsUs", "FromUnitToBaseFunc": "x*1.054804e8", "FromBaseToUnitFunc": "x/1.054804e8", - "Prefixes": [ "Deca" ], + "Prefixes": ["Deca"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "th (U.S.)" ], + "Abbreviations": ["th (U.S.)"], "AbbreviationsForPrefixes": { "Deca": "Dth (U.S.)" } }, { "Culture": "ru-RU", - "Abbreviations": [ "Американский терм" ], + "Abbreviations": ["Американский терм"], "AbbreviationsForPrefixes": { "Deca": "Американский декатерм" } } ] @@ -148,19 +149,19 @@ "PluralName": "ThermsImperial", "FromUnitToBaseFunc": "x*1.05505585257348e8", "FromBaseToUnitFunc": "x/1.05505585257348e8", - "Prefixes": [ "Deca" ], + "Prefixes": ["Deca"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "th (imp.)" ], + "Abbreviations": ["th (imp.)"], "AbbreviationsForPrefixes": { "Deca": "Dth (imp.)" } }, { "Culture": "ru-RU", - "Abbreviations": [ "Английский терм" ], + "Abbreviations": ["Английский терм"], "AbbreviationsForPrefixes": { "Deca": "Английский декатерм" } } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/Entropy.json b/Common/UnitDefinitions/Entropy.json index c723e866c0..4ebd3429f7 100644 --- a/Common/UnitDefinitions/Entropy.json +++ b/Common/UnitDefinitions/Entropy.json @@ -1,7 +1,8 @@ { "Name": "Entropy", "BaseUnit": "JoulePerKelvin", - "XmlDoc": "Entropy is an important concept in the branch of science known as thermodynamics. The idea of \"irreversibility\" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units", + "XmlDoc": + "Entropy is an important concept in the branch of science known as thermodynamics. The idea of \"irreversibility\" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units", "BaseDimensions": { "L": 2, "M": 1, @@ -14,11 +15,11 @@ "PluralName": "JoulesPerKelvin", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/K" ] + "Abbreviations": ["J/K"] } ] }, @@ -27,11 +28,11 @@ "PluralName": "CaloriesPerKelvin", "FromUnitToBaseFunc": "x*4.184", "FromBaseToUnitFunc": "x/4.184", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cal/K" ] + "Abbreviations": ["cal/K"] } ] }, @@ -40,13 +41,13 @@ "PluralName": "JoulesPerDegreeCelsius", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/C" ] + "Abbreviations": ["J/C"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/Force.json b/Common/UnitDefinitions/Force.json index aebf6a9ed9..0594836042 100644 --- a/Common/UnitDefinitions/Force.json +++ b/Common/UnitDefinitions/Force.json @@ -1,7 +1,8 @@ { "Name": "Force", "BaseUnit": "Newton", - "XmlDoc": "In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F.", + "XmlDoc": + "In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F.", "BaseDimensions": { "L": 1, "M": 1, @@ -21,11 +22,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dyn" ] + "Abbreviations": ["dyn"] }, { "Culture": "ru-RU", - "Abbreviations": [ "дин" ] + "Abbreviations": ["дин"] } ] }, @@ -37,11 +38,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf" ] + "Abbreviations": ["kgf"] }, { "Culture": "ru-RU", - "Abbreviations": [ "кгс" ] + "Abbreviations": ["кгс"] } ] }, @@ -53,11 +54,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Ton" ] + "Abbreviations": ["Ton"] }, { "Culture": "ru-RU", - "Abbreviations": [ "тс" ] + "Abbreviations": ["тс"] } ] }, @@ -71,15 +72,15 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Micro", "Milli", "Deca", "Kilo", "Mega" ], + "Prefixes": ["Micro", "Milli", "Deca", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N" ] + "Abbreviations": ["N"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Н" ] + "Abbreviations": ["Н"] } ] }, @@ -91,11 +92,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kp" ] + "Abbreviations": ["kp"] }, { "Culture": "ru-RU", - "Abbreviations": [ "кгс" ] + "Abbreviations": ["кгс"] } ] }, @@ -112,11 +113,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "pdl" ] + "Abbreviations": ["pdl"] }, { "Culture": "ru-RU", - "Abbreviations": [ "паундаль" ] + "Abbreviations": ["паундаль"] } ] }, @@ -128,11 +129,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf" ] + "Abbreviations": ["lbf"] }, { "Culture": "ru-RU", - "Abbreviations": [ "фунт-сила" ] + "Abbreviations": ["фунт-сила"] } ] }, @@ -144,9 +145,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ozf" ] + "Abbreviations": ["ozf"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/ForceChangeRate.json b/Common/UnitDefinitions/ForceChangeRate.json index f6969c638f..3442d4d597 100644 --- a/Common/UnitDefinitions/ForceChangeRate.json +++ b/Common/UnitDefinitions/ForceChangeRate.json @@ -1,7 +1,8 @@ { "Name": "ForceChangeRate", "BaseUnit": "NewtonPerSecond", - "XmlDoc": "Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time).", + "XmlDoc": + "Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time).", "BaseDimensions": { "L": 1, "M": 1, @@ -13,11 +14,11 @@ "PluralName": "NewtonsPerMinute", "FromUnitToBaseFunc": "x/60", "FromBaseToUnitFunc": "x*60", - "Prefixes": [ "Deca", "Kilo" ], + "Prefixes": ["Deca", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N/min" ] + "Abbreviations": ["N/min"] } ] }, @@ -26,11 +27,11 @@ "PluralName": "NewtonsPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N/s" ] + "Abbreviations": ["N/s"] } ] } diff --git a/Common/UnitDefinitions/ForcePerLength.json b/Common/UnitDefinitions/ForcePerLength.json index fa587153e2..1281d1397c 100644 --- a/Common/UnitDefinitions/ForcePerLength.json +++ b/Common/UnitDefinitions/ForcePerLength.json @@ -12,11 +12,11 @@ "PluralName": "NewtonsPerMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N/m" ] + "Abbreviations": ["N/m"] } ] }, @@ -28,11 +28,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf/m" ] + "Abbreviations": ["kgf/m"] }, { "Culture": "ru-RU", - "Abbreviations": [ "кгс/м" ] + "Abbreviations": ["кгс/м"] } ] }, @@ -44,7 +44,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf/ft" ] + "Abbreviations": ["lbf/ft"] } ] }, @@ -56,7 +56,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf/in" ] + "Abbreviations": ["lbf/in"] } ] }, @@ -68,7 +68,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf/yd" ] + "Abbreviations": ["lbf/yd"] } ] } diff --git a/Common/UnitDefinitions/Frequency.json b/Common/UnitDefinitions/Frequency.json index 9d60cdd35e..8acbfc4d18 100644 --- a/Common/UnitDefinitions/Frequency.json +++ b/Common/UnitDefinitions/Frequency.json @@ -11,11 +11,11 @@ "PluralName": "Hertz", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega", "Giga", "Tera" ], + "Prefixes": ["Kilo", "Mega", "Giga", "Tera"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Hz" ] + "Abbreviations": ["Hz"] } ] }, @@ -28,7 +28,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "rad/s" ] + "Abbreviations": ["rad/s"] } ] }, @@ -40,7 +40,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cpm" ] + "Abbreviations": ["cpm"] } ] }, @@ -52,7 +52,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cph" ] + "Abbreviations": ["cph"] } ] }, @@ -64,9 +64,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bpm" ] + "Abbreviations": ["bpm"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/FuelEfficiency.json b/Common/UnitDefinitions/FuelEfficiency.json index 2da60218f7..830c5eab42 100644 --- a/Common/UnitDefinitions/FuelEfficiency.json +++ b/Common/UnitDefinitions/FuelEfficiency.json @@ -1,55 +1,65 @@ { - "Name": "FuelEfficiency", - "BaseUnit": "LiterPer100Kilometers", - "XmlDoc": "Fuel efficiency is a form of thermal efficiency, meaning the ratio from effort to result of a process that converts chemical potential energy contained in a carrier (fuel) into kinetic energy or work. Fuel economy is stated as \"fuel consumption\" in liters per 100 kilometers (L/100 km). In countries using non-metric system, fuel economy is expressed in miles per gallon (mpg) (imperial galon or US galon).", - "XmlDocRemarks": "https://en.wikipedia.org/wiki/Fuel_efficiency", - "Units": [{ - "SingularName": "LiterPer100Kilometers", - "PluralName": "LitersPer100Kilometers", - "FromUnitToBaseFunc": "x", - "FromBaseToUnitFunc": "x", - "Localization": [{ + "Name": "FuelEfficiency", + "BaseUnit": "LiterPer100Kilometers", + "XmlDoc": + "Fuel efficiency is a form of thermal efficiency, meaning the ratio from effort to result of a process that converts chemical potential energy contained in a carrier (fuel) into kinetic energy or work. Fuel economy is stated as \"fuel consumption\" in liters per 100 kilometers (L/100 km). In countries using non-metric system, fuel economy is expressed in miles per gallon (mpg) (imperial galon or US galon).", + "XmlDocRemarks": "https://en.wikipedia.org/wiki/Fuel_efficiency", + "Units": [ + { + "SingularName": "LiterPer100Kilometers", + "PluralName": "LitersPer100Kilometers", + "FromUnitToBaseFunc": "x", + "FromBaseToUnitFunc": "x", + "Localization": [ + { "Culture": "en-US", "Abbreviations": [ "L/100km" ] - }] - }, - { - "SingularName": "MilePerUsGallon", - "PluralName": "MilesPerUsGallon", - "FromUnitToBaseFunc": "(100*3.785411784)/(1.609344*x)", - "FromBaseToUnitFunc": "(100*3.785411784)/(1.609344*x)", - "Localization": [{ + } + ] + }, + { + "SingularName": "MilePerUsGallon", + "PluralName": "MilesPerUsGallon", + "FromUnitToBaseFunc": "(100*3.785411784)/(1.609344*x)", + "FromBaseToUnitFunc": "(100*3.785411784)/(1.609344*x)", + "Localization": [ + { "Culture": "en-US", "Abbreviations": [ "mpg (U.S.)" ] - }] - }, - { - "SingularName": "MilePerUkGallon", - "PluralName": "MilesPerUkGallon", - "FromUnitToBaseFunc": "(100*4.54609188)/(1.609344*x)", - "FromBaseToUnitFunc": "(100*4.54609188)/(1.609344*x)", - "Localization": [{ + } + ] + }, + { + "SingularName": "MilePerUkGallon", + "PluralName": "MilesPerUkGallon", + "FromUnitToBaseFunc": "(100*4.54609188)/(1.609344*x)", + "FromBaseToUnitFunc": "(100*4.54609188)/(1.609344*x)", + "Localization": [ + { "Culture": "en-US", "Abbreviations": [ "mpg (imp.)" ] - }] - }, - { - "SingularName": "KilometerPerLiter", - "PluralName": "KilometersPerLiters", - "FromUnitToBaseFunc": "100/x", - "FromBaseToUnitFunc": "100/x", - "Localization": [{ + } + ] + }, + { + "SingularName": "KilometerPerLiter", + "PluralName": "KilometersPerLiters", + "FromUnitToBaseFunc": "100/x", + "FromBaseToUnitFunc": "100/x", + "Localization": [ + { "Culture": "en-US", "Abbreviations": [ "km/L" ] - }] - } - ] - } \ No newline at end of file + } + ] + } + ] +} \ No newline at end of file diff --git a/Common/UnitDefinitions/HeatFlux.json b/Common/UnitDefinitions/HeatFlux.json index aaa1658ef9..945bf0b079 100644 --- a/Common/UnitDefinitions/HeatFlux.json +++ b/Common/UnitDefinitions/HeatFlux.json @@ -16,11 +16,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/m²" ] + "Abbreviations": ["W/m²"] } ] }, @@ -32,7 +32,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/in²" ] + "Abbreviations": ["W/in²"] } ] }, @@ -44,7 +44,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/ft²" ] + "Abbreviations": ["W/ft²"] } ] }, @@ -56,7 +56,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "BTU/s·in²" ] + "Abbreviations": ["BTU/s·in²"] } ] }, @@ -68,7 +68,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "BTU/s·ft²" ] + "Abbreviations": ["BTU/s·ft²"] } ] }, @@ -80,7 +80,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "BTU/min·ft²" ] + "Abbreviations": ["BTU/min·ft²"] } ] }, @@ -92,7 +92,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "BTU/h·ft²" ] + "Abbreviations": ["BTU/h·ft²"] } ] }, @@ -101,11 +101,11 @@ "PluralName": "CaloriesPerSecondSquareCentimeter", "FromUnitToBaseFunc": "x*4.1868e4", "FromBaseToUnitFunc": "x/4.1868e4", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cal/s·cm²" ] + "Abbreviations": ["cal/s·cm²"] } ] }, @@ -117,7 +117,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kcal/h·m²" ] + "Abbreviations": ["kcal/h·m²"] } ] }, @@ -129,7 +129,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf/(ft·s)" ] + "Abbreviations": ["lbf/(ft·s)"] } ] }, @@ -141,7 +141,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/s³", "lbm/s³" ] + "Abbreviations": ["lb/s³", "lbm/s³"] } ] } diff --git a/Common/UnitDefinitions/HeatTransferCoefficient.json b/Common/UnitDefinitions/HeatTransferCoefficient.json index 97220b1efa..660b1f86de 100644 --- a/Common/UnitDefinitions/HeatTransferCoefficient.json +++ b/Common/UnitDefinitions/HeatTransferCoefficient.json @@ -1,7 +1,8 @@ { "Name": "HeatTransferCoefficient", "BaseUnit": "WattPerSquareMeterKelvin", - "XmlDoc": "The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT)", + "XmlDoc": + "The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT)", "BaseDimensions": { "M": 1, "T": -3, @@ -16,7 +17,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/m²·K" ] + "Abbreviations": ["W/m²·K"] } ] }, @@ -28,7 +29,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/m²·°C" ] + "Abbreviations": ["W/m²·°C"] } ] }, @@ -40,7 +41,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Btu/ft²·hr·°F" ] + "Abbreviations": ["Btu/ft²·hr·°F"] } ] } diff --git a/Common/UnitDefinitions/Illuminance.json b/Common/UnitDefinitions/Illuminance.json index c5fc7f0b08..45dc02bdd9 100644 --- a/Common/UnitDefinitions/Illuminance.json +++ b/Common/UnitDefinitions/Illuminance.json @@ -13,11 +13,11 @@ "PluralName": "Lux", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Milli", "Kilo", "Mega" ], + "Prefixes": ["Milli", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lx" ] + "Abbreviations": ["lx"] } ] } diff --git a/Common/UnitDefinitions/Information.json b/Common/UnitDefinitions/Information.json index 7c28cad347..c521b6b631 100644 --- a/Common/UnitDefinitions/Information.json +++ b/Common/UnitDefinitions/Information.json @@ -2,18 +2,19 @@ "Name": "Information", "BaseUnit": "Bit", "BaseType": "decimal", - "XmlDoc": "In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables.", + "XmlDoc": + "In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables.", "Units": [ { "SingularName": "Byte", "PluralName": "Bytes", "FromUnitToBaseFunc": "x*8m", "FromBaseToUnitFunc": "x/8m", - "Prefixes": [ "Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi" ], + "Prefixes": ["Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "B" ] + "Abbreviations": ["B"] } ] }, @@ -22,11 +23,11 @@ "PluralName": "Bits", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi" ], + "Prefixes": ["Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "b" ] + "Abbreviations": ["b"] } ] } diff --git a/Common/UnitDefinitions/Irradiance.json b/Common/UnitDefinitions/Irradiance.json index 0c3bfd7a3a..c47152d9bd 100644 --- a/Common/UnitDefinitions/Irradiance.json +++ b/Common/UnitDefinitions/Irradiance.json @@ -12,11 +12,11 @@ "PluralName": "WattsPerSquareMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Kilo", "Mega" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/m²" ] + "Abbreviations": ["W/m²"] } ] }, @@ -25,11 +25,11 @@ "PluralName": "WattsPerSquareCentimeter", "FromUnitToBaseFunc": "x*10000", "FromBaseToUnitFunc": "x*0.0001", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Kilo", "Mega" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/cm²" ] + "Abbreviations": ["W/cm²"] } ] } diff --git a/Common/UnitDefinitions/Irradiation.json b/Common/UnitDefinitions/Irradiation.json index 4d6617a85a..0318fa3983 100644 --- a/Common/UnitDefinitions/Irradiation.json +++ b/Common/UnitDefinitions/Irradiation.json @@ -1,7 +1,8 @@ { "Name": "Irradiation", "BaseUnit": "JoulePerSquareMeter", - "XmlDoc": "Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources.", + "XmlDoc": + "Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Irradiation", "BaseDimensions": { "M": 1, @@ -13,11 +14,11 @@ "PluralName": "JoulesPerSquareMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/m²" ] + "Abbreviations": ["J/m²"] } ] }, @@ -26,11 +27,11 @@ "PluralName": "JoulesPerSquareCentimeter", "FromUnitToBaseFunc": "x*1e4", "FromBaseToUnitFunc": "x/1e4", - "Prefixes": [ "Milli" ], + "Prefixes": ["Milli"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/cm²" ] + "Abbreviations": ["J/cm²"] } ] }, @@ -42,7 +43,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/mm²" ] + "Abbreviations": ["J/mm²"] } ] }, @@ -51,11 +52,11 @@ "PluralName": "WattHoursPerSquareMeter", "FromUnitToBaseFunc": "x*3600d", "FromBaseToUnitFunc": "x/3600d", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Wh/m²" ] + "Abbreviations": ["Wh/m²"] } ] } diff --git a/Common/UnitDefinitions/KinematicViscosity.json b/Common/UnitDefinitions/KinematicViscosity.json index c4d1d07bb5..14e27ded57 100644 --- a/Common/UnitDefinitions/KinematicViscosity.json +++ b/Common/UnitDefinitions/KinematicViscosity.json @@ -1,7 +1,8 @@ { "Name": "KinematicViscosity", "BaseUnit": "SquareMeterPerSecond", - "XmlDoc": "The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress.", + "XmlDoc": + "The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Viscosity", "BaseDimensions": { "L": 2, @@ -16,11 +17,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m²/s" ] + "Abbreviations": ["m²/s"] }, { "Culture": "ru-RU", - "Abbreviations": [ "м²/с" ] + "Abbreviations": ["м²/с"] } ] }, @@ -29,17 +30,17 @@ "PluralName": "Stokes", "FromUnitToBaseFunc": "x/1e4", "FromBaseToUnitFunc": "x*1e4", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "St" ] + "Abbreviations": ["St"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Ст" ] + "Abbreviations": ["Ст"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/LapseRate.json b/Common/UnitDefinitions/LapseRate.json index 782eec865b..e2ae25f8eb 100644 --- a/Common/UnitDefinitions/LapseRate.json +++ b/Common/UnitDefinitions/LapseRate.json @@ -1,7 +1,8 @@ { "Name": "LapseRate", "BaseUnit": "DegreeCelsiusPerKilometer", - "XmlDoc": "Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude.", + "XmlDoc": + "Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude.", "BaseDimensions": { "L": -1, "Θ": 1 @@ -15,7 +16,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "∆°C/km" ] + "Abbreviations": ["∆°C/km"] } ] } diff --git a/Common/UnitDefinitions/Length.json b/Common/UnitDefinitions/Length.json index de016ce60e..7034622490 100644 --- a/Common/UnitDefinitions/Length.json +++ b/Common/UnitDefinitions/Length.json @@ -1,7 +1,8 @@ { "Name": "Length", "BaseUnit": "Meter", - "XmlDoc": "Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units.", + "XmlDoc": + "Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units.", "BaseDimensions": { "L": 1 }, @@ -14,15 +15,15 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Hecto", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Hecto", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m" ] + "Abbreviations": ["m"] }, { "Culture": "ru-RU", - "Abbreviations": [ "м" ] + "Abbreviations": ["м"] } ] }, @@ -37,11 +38,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mi" ] + "Abbreviations": ["mi"] }, { "Culture": "ru-RU", - "Abbreviations": [ "миля" ] + "Abbreviations": ["миля"] } ] }, @@ -56,11 +57,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "yd" ] + "Abbreviations": ["yd"] }, { "Culture": "ru-RU", - "Abbreviations": [ "ярд" ] + "Abbreviations": ["ярд"] } ] }, @@ -75,11 +76,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft", "'", "′" ] + "Abbreviations": ["ft", "'", "′"] }, { "Culture": "ru-RU", - "Abbreviations": [ "фут" ] + "Abbreviations": ["фут"] } ] }, @@ -94,7 +95,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ftUS" ] + "Abbreviations": ["ftUS"] } ] }, @@ -109,11 +110,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "in", "\\\"", "″" ] + "Abbreviations": ["in", "\\\"", "″"] }, { "Culture": "ru-RU", - "Abbreviations": [ "дюйм" ] + "Abbreviations": ["дюйм"] } ] }, @@ -128,11 +129,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mil" ] + "Abbreviations": ["mil"] }, { "Culture": "ru-RU", - "Abbreviations": [ "мил" ] + "Abbreviations": ["мил"] } ] }, @@ -147,11 +148,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "NM" ] + "Abbreviations": ["NM"] }, { "Culture": "ru-RU", - "Abbreviations": [ "мил" ] + "Abbreviations": ["мил"] } ] }, @@ -166,7 +167,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "fathom" ] + "Abbreviations": ["fathom"] } ] }, @@ -181,7 +182,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "shackle" ] + "Abbreviations": ["shackle"] } ] }, @@ -196,11 +197,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "µin" ] + "Abbreviations": ["µin"] }, { "Culture": "ru-RU", - "Abbreviations": [ "микродюйм" ] + "Abbreviations": ["микродюйм"] } ] }, @@ -215,7 +216,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "pt" ] + "Abbreviations": ["pt"] } ] }, @@ -230,7 +231,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "pt" ] + "Abbreviations": ["pt"] } ] }, @@ -245,7 +246,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "pica" ] + "Abbreviations": ["pica"] } ] }, @@ -260,7 +261,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "pica" ] + "Abbreviations": ["pica"] } ] }, @@ -275,7 +276,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "twip" ] + "Abbreviations": ["twip"] } ] }, @@ -290,7 +291,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "h", "hh" ] + "Abbreviations": ["h", "hh"] } ] }, @@ -304,7 +305,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "au", "ua" ] + "Abbreviations": ["au", "ua"] } ] }, @@ -313,13 +314,14 @@ "PluralName": "Parsecs", "FromUnitToBaseFunc": "x * 3.08567758128e16", "FromBaseToUnitFunc": "x / 3.08567758128e16", - "XmlDocSummary": "A parsec is defined as the distance at which one astronomical unit (AU) subtends an angle of one arcsecond.", + "XmlDocSummary": + "A parsec is defined as the distance at which one astronomical unit (AU) subtends an angle of one arcsecond.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Parsec", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "pc" ] + "Abbreviations": ["pc"] } ] }, @@ -330,11 +332,11 @@ "FromBaseToUnitFunc": "x / 9.46073047258e15", "XmlDocSummary": "A Light Year (ly) is the distance that light travel during an Earth year, ie 365 days.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Light-year", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ly" ] + "Abbreviations": ["ly"] } ] }, @@ -348,9 +350,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "R⊙" ] + "Abbreviations": ["R⊙"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/Level.json b/Common/UnitDefinitions/Level.json index f014fcb2eb..b8e51ae572 100644 --- a/Common/UnitDefinitions/Level.json +++ b/Common/UnitDefinitions/Level.json @@ -3,7 +3,8 @@ "BaseUnit": "Decibel", "Logarithmic": "True", "LogarithmicScalingFactor": "1", - "XmlDoc": "Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units.", + "XmlDoc": + "Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units.", "Units": [ { "SingularName": "Decibel", @@ -13,7 +14,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dB" ] + "Abbreviations": ["dB"] } ] }, @@ -25,7 +26,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Np" ] + "Abbreviations": ["Np"] } ] } diff --git a/Common/UnitDefinitions/LinearDensity.json b/Common/UnitDefinitions/LinearDensity.json index ab068224b6..d85ba98de7 100644 --- a/Common/UnitDefinitions/LinearDensity.json +++ b/Common/UnitDefinitions/LinearDensity.json @@ -1,7 +1,8 @@ { "Name": "LinearDensity", "BaseUnit": "KilogramPerMeter", - "XmlDoc": "The Linear Density, or more precisely, the linear mass density, of a substance is its mass per unit length. The term linear density is most often used when describing the characteristics of one-dimensional objects, although linear density can also be used to describe the density of a three-dimensional quantity along one particular dimension.", + "XmlDoc": + "The Linear Density, or more precisely, the linear mass density, of a substance is its mass per unit length. The term linear density is most often used when describing the characteristics of one-dimensional objects, although linear density can also be used to describe the density of a three-dimensional quantity along one particular dimension.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Linear_density", "BaseDimensions": { "L": -1, @@ -13,11 +14,11 @@ "PluralName": "GramsPerMeter", "FromUnitToBaseFunc": "x*1e-3", "FromBaseToUnitFunc": "x/1e-3", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/m" ] + "Abbreviations": ["g/m"] } ] }, @@ -29,7 +30,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/ft" ] + "Abbreviations": ["lb/ft"] } ] } diff --git a/Common/UnitDefinitions/Luminosity.json b/Common/UnitDefinitions/Luminosity.json index 59a1d82efd..005e7b6521 100644 --- a/Common/UnitDefinitions/Luminosity.json +++ b/Common/UnitDefinitions/Luminosity.json @@ -2,7 +2,8 @@ "Name": "Luminosity", "BaseUnit": "Watt", "BaseType": "double", - "XmlDoc": "Luminosity is an absolute measure of radiated electromagnetic power (light), the radiant power emitted by a light-emitting object.", + "XmlDoc": + "Luminosity is an absolute measure of radiated electromagnetic power (light), the radiant power emitted by a light-emitting object.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Luminosity", "BaseDimensions": { "L": 2, @@ -15,11 +16,11 @@ "PluralName": "Watts", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Femto", "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera", "Peta" ], + "Prefixes": ["Femto", "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera", "Peta"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W" ] + "Abbreviations": ["W"] } ] }, @@ -32,7 +33,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "L⊙" ] + "Abbreviations": ["L⊙"] } ] } diff --git a/Common/UnitDefinitions/LuminousFlux.json b/Common/UnitDefinitions/LuminousFlux.json index 3307cc700c..5bfcbb6bf9 100644 --- a/Common/UnitDefinitions/LuminousFlux.json +++ b/Common/UnitDefinitions/LuminousFlux.json @@ -15,7 +15,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lm" ] + "Abbreviations": ["lm"] } ] } diff --git a/Common/UnitDefinitions/LuminousIntensity.json b/Common/UnitDefinitions/LuminousIntensity.json index f32f634628..173985037c 100644 --- a/Common/UnitDefinitions/LuminousIntensity.json +++ b/Common/UnitDefinitions/LuminousIntensity.json @@ -1,7 +1,8 @@ { "Name": "LuminousIntensity", "BaseUnit": "Candela", - "XmlDoc": "In photometry, luminous intensity is a measure of the wavelength-weighted power emitted by a light source in a particular direction per unit solid angle, based on the luminosity function, a standardized model of the sensitivity of the human eye.", + "XmlDoc": + "In photometry, luminous intensity is a measure of the wavelength-weighted power emitted by a light source in a particular direction per unit solid angle, based on the luminosity function, a standardized model of the sensitivity of the human eye.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Luminous_intensity", "BaseDimensions": { "J": 1 @@ -18,7 +19,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cd" ] + "Abbreviations": ["cd"] } ] } diff --git a/Common/UnitDefinitions/MagneticField.json b/Common/UnitDefinitions/MagneticField.json index 9eafc9769c..8aebaebaaf 100644 --- a/Common/UnitDefinitions/MagneticField.json +++ b/Common/UnitDefinitions/MagneticField.json @@ -1,7 +1,8 @@ { "Name": "MagneticField", "BaseUnit": "Tesla", - "XmlDoc": "A magnetic field is a force field that is created by moving electric charges (electric currents) and magnetic dipoles, and exerts a force on other nearby moving charges and magnetic dipoles.", + "XmlDoc": + "A magnetic field is a force field that is created by moving electric charges (electric currents) and magnetic dipoles, and exerts a force on other nearby moving charges and magnetic dipoles.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Magnetic_field", "BaseDimensions": { "M": 1, @@ -14,11 +15,11 @@ "PluralName": "Teslas", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli" ], + "Prefixes": ["Nano", "Micro", "Milli"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "T" ] + "Abbreviations": ["T"] } ] } diff --git a/Common/UnitDefinitions/MagneticFlux.json b/Common/UnitDefinitions/MagneticFlux.json index 92bb40ce26..9a9a03bd1e 100644 --- a/Common/UnitDefinitions/MagneticFlux.json +++ b/Common/UnitDefinitions/MagneticFlux.json @@ -1,7 +1,8 @@ { "Name": "MagneticFlux", "BaseUnit": "Weber", - "XmlDoc": "In physics, specifically electromagnetism, the magnetic flux through a surface is the surface integral of the normal component of the magnetic field B passing through that surface.", + "XmlDoc": + "In physics, specifically electromagnetism, the magnetic flux through a surface is the surface integral of the normal component of the magnetic field B passing through that surface.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Magnetic_flux", "BaseDimensions": { "L": 2, @@ -18,7 +19,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Wb" ] + "Abbreviations": ["Wb"] } ] } diff --git a/Common/UnitDefinitions/Magnetization.json b/Common/UnitDefinitions/Magnetization.json index 6b15c37a48..30ba967619 100644 --- a/Common/UnitDefinitions/Magnetization.json +++ b/Common/UnitDefinitions/Magnetization.json @@ -1,7 +1,8 @@ { "Name": "Magnetization", "BaseUnit": "AmperePerMeter", - "XmlDoc": "In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material.", + "XmlDoc": + "In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Magnetization", "BaseDimensions": { "L": -1, @@ -20,7 +21,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "A/m" ] + "Abbreviations": ["A/m"] } ] } diff --git a/Common/UnitDefinitions/Mass.json b/Common/UnitDefinitions/Mass.json index ab018920e2..a820435bcf 100644 --- a/Common/UnitDefinitions/Mass.json +++ b/Common/UnitDefinitions/Mass.json @@ -1,7 +1,8 @@ { "Name": "Mass", "BaseUnit": "Kilogram", - "XmlDoc": "In physics, mass (from Greek μᾶζα \"barley cake, lump [of dough]\") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg).", + "XmlDoc": + "In physics, mass (from Greek μᾶζα \"barley cake, lump [of dough]\") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg).", "BaseDimensions": { "M": 1 }, @@ -14,15 +15,15 @@ }, "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g" ] + "Abbreviations": ["g"] }, { "Culture": "ru-RU", - "Abbreviations": [ "г" ] + "Abbreviations": ["г"] } ] }, @@ -34,15 +35,15 @@ }, "FromUnitToBaseFunc": "x*1e3", "FromBaseToUnitFunc": "x/1e3", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t" ] + "Abbreviations": ["t"] }, { "Culture": "ru-RU", - "Abbreviations": [ "т" ] + "Abbreviations": ["т"] } ] }, @@ -54,16 +55,17 @@ }, "FromUnitToBaseFunc": "x*9.0718474e2", "FromBaseToUnitFunc": "x/9.0718474e2", - "XmlDocSummary": "The short ton is a unit of mass equal to 2,000 pounds (907.18474 kg), that is most commonly used in the United States – known there simply as the ton.", + "XmlDocSummary": + "The short ton is a unit of mass equal to 2,000 pounds (907.18474 kg), that is most commonly used in the United States – known there simply as the ton.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Short_ton", "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "short tn" ] + "Abbreviations": ["short tn"] }, { "Culture": "ru-RU", - "Abbreviations": [ "тонна малая" ] + "Abbreviations": ["тонна малая"] } ] }, @@ -75,16 +77,17 @@ }, "FromUnitToBaseFunc": "x*1.0160469088e3", "FromBaseToUnitFunc": "x/1.0160469088e3", - "XmlDocSummary": "Long ton (weight ton or Imperial ton) is a unit of mass equal to 2,240 pounds (1,016 kg) and is the name for the unit called the \"ton\" in the avoirdupois or Imperial system of measurements that was used in the United Kingdom and several other Commonwealth countries before metrication.", + "XmlDocSummary": + "Long ton (weight ton or Imperial ton) is a unit of mass equal to 2,240 pounds (1,016 kg) and is the name for the unit called the \"ton\" in the avoirdupois or Imperial system of measurements that was used in the United Kingdom and several other Commonwealth countries before metrication.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Long_ton", "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "long tn" ] + "Abbreviations": ["long tn"] }, { "Culture": "ru-RU", - "Abbreviations": [ "тонна большая" ] + "Abbreviations": ["тонна большая"] } ] }, @@ -96,16 +99,17 @@ }, "FromUnitToBaseFunc": "x*0.45359237", "FromBaseToUnitFunc": "x/0.45359237", - "XmlDocSummary": "The pound or pound-mass (abbreviations: lb, lbm) is a unit of mass used in the imperial, United States customary and other systems of measurement. A number of different definitions have been used, the most common today being the international avoirdupois pound which is legally defined as exactly 0.45359237 kilograms, and which is divided into 16 avoirdupois ounces.", - "Prefixes": [ "Kilo", "Mega" ], + "XmlDocSummary": + "The pound or pound-mass (abbreviations: lb, lbm) is a unit of mass used in the imperial, United States customary and other systems of measurement. A number of different definitions have been used, the most common today being the international avoirdupois pound which is legally defined as exactly 0.45359237 kilograms, and which is divided into 16 avoirdupois ounces.", + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb", "lbs", "lbm" ] + "Abbreviations": ["lb", "lbs", "lbm"] }, { "Culture": "ru-RU", - "Abbreviations": [ "фунт" ] + "Abbreviations": ["фунт"] } ] }, @@ -117,12 +121,13 @@ }, "FromUnitToBaseFunc": "x/35.2739619", "FromBaseToUnitFunc": "x*35.2739619", - "XmlDocSummary": "An ounce (abbreviated oz) is usually the international avoirdupois ounce as used in the United States customary and British imperial systems, which is equal to one-sixteenth of a pound or approximately 28 grams. The abbreviation 'oz' derives from the Italian word onza (now spelled oncia).", + "XmlDocSummary": + "An ounce (abbreviated oz) is usually the international avoirdupois ounce as used in the United States customary and British imperial systems, which is equal to one-sixteenth of a pound or approximately 28 grams. The abbreviation 'oz' derives from the Italian word onza (now spelled oncia).", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Ounce", "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "oz" ] + "Abbreviations": ["oz"] } ] }, @@ -134,12 +139,13 @@ }, "FromUnitToBaseFunc": "x/6.852176556196105e-2", "FromBaseToUnitFunc": "x*6.852176556196105e-2", - "XmlDocSummary": "The slug (abbreviation slug) is a unit of mass that is accelerated by 1 ft/s² when a force of one pound (lbf) is exerted on it.", + "XmlDocSummary": + "The slug (abbreviation slug) is a unit of mass that is accelerated by 1 ft/s² when a force of one pound (lbf) is exerted on it.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Slug_(unit)", "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "slug" ] + "Abbreviations": ["slug"] } ] }, @@ -151,12 +157,13 @@ }, "FromUnitToBaseFunc": "x/0.1574731728702698", "FromBaseToUnitFunc": "x*0.1574731728702698", - "XmlDocSummary": "The stone (abbreviation st) is a unit of mass equal to 14 pounds avoirdupois (about 6.35 kilograms) used in Great Britain and Ireland for measuring human body weight.", + "XmlDocSummary": + "The stone (abbreviation st) is a unit of mass equal to 14 pounds avoirdupois (about 6.35 kilograms) used in Great Britain and Ireland for measuring human body weight.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Stone_(unit)", "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "st" ] + "Abbreviations": ["st"] } ] }, @@ -168,12 +175,13 @@ }, "FromUnitToBaseFunc": "x/0.022046226218487758", "FromBaseToUnitFunc": "x*0.022046226218487758", - "XmlDocSummary": "The short hundredweight (abbreviation cwt) is a unit of mass equal to 100 pounds in US and Canada. In British English, the short hundredweight is referred to as the \"cental\".", + "XmlDocSummary": + "The short hundredweight (abbreviation cwt) is a unit of mass equal to 100 pounds in US and Canada. In British English, the short hundredweight is referred to as the \"cental\".", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Hundredweight", "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cwt" ] + "Abbreviations": ["cwt"] } ] }, @@ -185,12 +193,13 @@ }, "FromUnitToBaseFunc": "x/0.01968413055222121", "FromBaseToUnitFunc": "x*0.01968413055222121", - "XmlDocSummary": "The long or imperial hundredweight (abbreviation cwt) is a unit of mass equal to 112 pounds in US and Canada.", + "XmlDocSummary": + "The long or imperial hundredweight (abbreviation cwt) is a unit of mass equal to 112 pounds in US and Canada.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Hundredweight", "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cwt" ] + "Abbreviations": ["cwt"] } ] }, @@ -202,12 +211,13 @@ }, "FromUnitToBaseFunc": "x/15432.358352941431", "FromBaseToUnitFunc": "x*15432.358352941431", - "XmlDocSummary": "A grain is a unit of measurement of mass, and in the troy weight, avoirdupois, and Apothecaries' system, equal to exactly 64.79891 milligrams.", + "XmlDocSummary": + "A grain is a unit of measurement of mass, and in the troy weight, avoirdupois, and Apothecaries' system, equal to exactly 64.79891 milligrams.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Grain_(unit)", "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gr" ] + "Abbreviations": ["gr"] } ] }, @@ -224,7 +234,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "M⊙" ] + "Abbreviations": ["M⊙"] } ] }, @@ -241,9 +251,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "em" ] + "Abbreviations": ["em"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/MassConcentration.json b/Common/UnitDefinitions/MassConcentration.json index 8aabae64fb..53ad08e0df 100644 --- a/Common/UnitDefinitions/MassConcentration.json +++ b/Common/UnitDefinitions/MassConcentration.json @@ -1,7 +1,8 @@ { "Name": "MassConcentration", "BaseUnit": "KilogramPerCubicMeter", - "XmlDoc": "In chemistry, the mass concentration ρi (or γi) is defined as the mass of a constituent mi divided by the volume of the mixture V", + "XmlDoc": + "In chemistry, the mass concentration ρi (or γi) is defined as the mass of a constituent mi divided by the volume of the mixture V", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Mass_concentration_(chemistry)", "BaseDimensions": { "M": 1, @@ -17,11 +18,11 @@ }, "FromUnitToBaseFunc": "x/1e-6", "FromBaseToUnitFunc": "x*1e-6", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/mm³" ] + "Abbreviations": ["g/mm³"] } ] }, @@ -34,11 +35,11 @@ }, "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/cm³" ] + "Abbreviations": ["g/cm³"] } ] }, @@ -51,15 +52,15 @@ }, "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": [ "Kilo", "Milli", "Micro" ], + "Prefixes": ["Kilo", "Milli", "Micro"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/m³" ] + "Abbreviations": ["g/m³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "г/м³" ] + "Abbreviations": ["г/м³"] } ] }, @@ -72,11 +73,11 @@ }, "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/mL" ] + "Abbreviations": ["g/mL"] } ] }, @@ -85,11 +86,11 @@ "PluralName": "GramsPerDeciliter", "FromUnitToBaseFunc": "x/1e-1", "FromBaseToUnitFunc": "x*1e-1", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/dL" ] + "Abbreviations": ["g/dL"] } ] }, @@ -102,11 +103,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/L"] + "Abbreviations": ["g/L"] } ] }, @@ -122,7 +123,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t/mm³" ] + "Abbreviations": ["t/mm³"] } ] }, @@ -138,7 +139,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t/cm³" ] + "Abbreviations": ["t/cm³"] } ] }, @@ -154,7 +155,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t/m³" ] + "Abbreviations": ["t/m³"] } ] }, @@ -167,11 +168,11 @@ }, "FromUnitToBaseFunc": "x/3.6127298147753e-5", "FromBaseToUnitFunc": "x*3.6127298147753e-5", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/in³" ], + "Abbreviations": ["lb/in³"], "AbbreviationsForPrefixes": { "Kilo": "kip/in³" } } ] @@ -185,11 +186,11 @@ }, "FromUnitToBaseFunc": "x/0.062427961", "FromBaseToUnitFunc": "x*0.062427961", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/ft³" ], + "Abbreviations": ["lb/ft³"], "AbbreviationsForPrefixes": { "Kilo": "kip/ft³" } } ] @@ -206,7 +207,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "slug/ft³" ] + "Abbreviations": ["slug/ft³"] } ] }, @@ -218,7 +219,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppg (U.S.)" ] + "Abbreviations": ["ppg (U.S.)"] } ] }, @@ -230,9 +231,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppg (imp.)" ] + "Abbreviations": ["ppg (imp.)"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/MassFlow.json b/Common/UnitDefinitions/MassFlow.json index fd012d7c5e..d5ea22477a 100644 --- a/Common/UnitDefinitions/MassFlow.json +++ b/Common/UnitDefinitions/MassFlow.json @@ -1,7 +1,8 @@ { "Name": "MassFlow", "BaseUnit": "GramPerSecond", - "XmlDoc": "Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time).", + "XmlDoc": + "Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time).", "BaseDimensions": { "M": 1, "T": -1 @@ -12,11 +13,11 @@ "PluralName": "GramsPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/s", "g/S" ] + "Abbreviations": ["g/s", "g/S"] } ] }, @@ -25,11 +26,11 @@ "PluralName": "GramsPerDay", "FromUnitToBaseFunc": "x/86400", "FromBaseToUnitFunc": "x*86400", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo", "Mega" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/d" ] + "Abbreviations": ["g/d"] } ] }, @@ -41,7 +42,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/h" ] + "Abbreviations": ["g/h"] } ] }, @@ -53,11 +54,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kg/h" ] + "Abbreviations": ["kg/h"] }, { "Culture": "ru-RU", - "Abbreviations": [ "кг/ч" ] + "Abbreviations": ["кг/ч"] } ] }, @@ -69,11 +70,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kg/min" ] + "Abbreviations": ["kg/min"] }, { "Culture": "ru-RU", - "Abbreviations": [ "кг/мин" ] + "Abbreviations": ["кг/мин"] } ] }, @@ -85,7 +86,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t/h" ] + "Abbreviations": ["t/h"] } ] }, @@ -94,11 +95,11 @@ "PluralName": "PoundsPerDay", "FromUnitToBaseFunc": "x/190.47936", "FromBaseToUnitFunc": "x*190.47936", - "Prefixes": [ "Mega" ], + "Prefixes": ["Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/d" ] + "Abbreviations": ["lb/d"] } ] }, @@ -107,11 +108,11 @@ "PluralName": "PoundsPerHour", "FromUnitToBaseFunc": "x/7.93664", "FromBaseToUnitFunc": "x*7.93664", - "Prefixes": [ "Mega" ], + "Prefixes": ["Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/h" ] + "Abbreviations": ["lb/h"] } ] }, @@ -120,11 +121,11 @@ "PluralName": "PoundsPerMinute", "FromUnitToBaseFunc": "x/0.132277", "FromBaseToUnitFunc": "x*0.132277", - "Prefixes": [ "Mega" ], + "Prefixes": ["Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/min" ] + "Abbreviations": ["lb/min"] } ] }, @@ -133,11 +134,11 @@ "PluralName": "PoundsPerSecond", "FromUnitToBaseFunc": "x * 453.59237", "FromBaseToUnitFunc": "x / 453.59237", - "Prefixes": [ "Mega" ], + "Prefixes": ["Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/s" ] + "Abbreviations": ["lb/s"] } ] }, @@ -149,7 +150,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t/d" ] + "Abbreviations": ["t/d"] } ] }, @@ -161,9 +162,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "short tn/h" ] + "Abbreviations": ["short tn/h"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/MassFlux.json b/Common/UnitDefinitions/MassFlux.json index 40799b9f38..2f20c47d14 100644 --- a/Common/UnitDefinitions/MassFlux.json +++ b/Common/UnitDefinitions/MassFlux.json @@ -13,11 +13,11 @@ "PluralName": "GramsPerSecondPerSquareMeter", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g·s⁻¹·m⁻²" ] + "Abbreviations": ["g·s⁻¹·m⁻²"] } ] } diff --git a/Common/UnitDefinitions/MassFraction.json b/Common/UnitDefinitions/MassFraction.json index fdfc016073..a4da8bca3f 100644 --- a/Common/UnitDefinitions/MassFraction.json +++ b/Common/UnitDefinitions/MassFraction.json @@ -4,7 +4,7 @@ "XmlDoc": "The mass fraction is defined as the mass of a constituent divided by the total mass of the mixture.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Mass_fraction_(chemistry)", "Units": [ - { + { "SingularName": "DecimalFraction", "PluralName": "DecimalFractions", "FromUnitToBaseFunc": "x", @@ -12,7 +12,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "" ] + "Abbreviations": [""] } ] }, @@ -21,11 +21,11 @@ "PluralName": "GramsPerGram", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/g" ] + "Abbreviations": ["g/g"] } ] }, @@ -34,11 +34,11 @@ "PluralName": "GramsPerKilogram", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/kg" ] + "Abbreviations": ["g/kg"] } ] }, @@ -50,7 +50,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "%", "% (w/w)" ] + "Abbreviations": ["%", "% (w/w)"] } ] }, @@ -62,7 +62,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "‰" ] + "Abbreviations": ["‰"] } ] }, @@ -74,7 +74,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppm" ] + "Abbreviations": ["ppm"] } ] }, @@ -86,7 +86,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppb" ] + "Abbreviations": ["ppb"] } ] }, @@ -98,7 +98,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppt" ] + "Abbreviations": ["ppt"] } ] } diff --git a/Common/UnitDefinitions/MassMomentOfInertia.json b/Common/UnitDefinitions/MassMomentOfInertia.json index da5357ddf6..3a80fd1207 100644 --- a/Common/UnitDefinitions/MassMomentOfInertia.json +++ b/Common/UnitDefinitions/MassMomentOfInertia.json @@ -12,11 +12,11 @@ "PluralName": "GramSquareMeters", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": [ "Milli", "Kilo" ], + "Prefixes": ["Milli", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g·m²" ] + "Abbreviations": ["g·m²"] } ] }, @@ -25,11 +25,11 @@ "PluralName": "GramSquareDecimeters", "FromUnitToBaseFunc": "x/1e5", "FromBaseToUnitFunc": "x*1e5", - "Prefixes": [ "Milli", "Kilo" ], + "Prefixes": ["Milli", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g·dm²" ] + "Abbreviations": ["g·dm²"] } ] }, @@ -38,11 +38,11 @@ "PluralName": "GramSquareCentimeters", "FromUnitToBaseFunc": "x/1e7", "FromBaseToUnitFunc": "x*1e7", - "Prefixes": [ "Milli", "Kilo" ], + "Prefixes": ["Milli", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g·cm²" ] + "Abbreviations": ["g·cm²"] } ] }, @@ -51,11 +51,11 @@ "PluralName": "GramSquareMillimeters", "FromUnitToBaseFunc": "x/1e9", "FromBaseToUnitFunc": "x*1e9", - "Prefixes": [ "Milli", "Kilo" ], + "Prefixes": ["Milli", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g·mm²" ] + "Abbreviations": ["g·mm²"] } ] }, @@ -64,11 +64,11 @@ "PluralName": "TonneSquareMeters", "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t·m²" ] + "Abbreviations": ["t·m²"] } ] }, @@ -77,11 +77,11 @@ "PluralName": "TonneSquareDecimeters", "FromUnitToBaseFunc": "x/1e-1", "FromBaseToUnitFunc": "x*1e-1", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t·dm²" ] + "Abbreviations": ["t·dm²"] } ] }, @@ -90,11 +90,11 @@ "PluralName": "TonneSquareCentimeters", "FromUnitToBaseFunc": "x/1e1", "FromBaseToUnitFunc": "x*1e1", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t·cm²" ] + "Abbreviations": ["t·cm²"] } ] }, @@ -103,11 +103,11 @@ "PluralName": "TonneSquareMilimeters", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "t·mm²" ] + "Abbreviations": ["t·mm²"] } ] }, @@ -119,7 +119,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb·ft²" ] + "Abbreviations": ["lb·ft²"] } ] }, @@ -131,7 +131,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb·in²" ] + "Abbreviations": ["lb·in²"] } ] }, @@ -143,7 +143,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "slug·ft²" ] + "Abbreviations": ["slug·ft²"] } ] }, @@ -155,7 +155,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "slug·in²" ] + "Abbreviations": ["slug·in²"] } ] } diff --git a/Common/UnitDefinitions/MolarEnergy.json b/Common/UnitDefinitions/MolarEnergy.json index ad95f79847..c7cd878358 100644 --- a/Common/UnitDefinitions/MolarEnergy.json +++ b/Common/UnitDefinitions/MolarEnergy.json @@ -14,13 +14,13 @@ "PluralName": "JoulesPerMole", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/mol" ] + "Abbreviations": ["J/mol"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/MolarEntropy.json b/Common/UnitDefinitions/MolarEntropy.json index d7bceaf21d..62685231cc 100644 --- a/Common/UnitDefinitions/MolarEntropy.json +++ b/Common/UnitDefinitions/MolarEntropy.json @@ -15,13 +15,13 @@ "PluralName": "JoulesPerMoleKelvin", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/(mol*K)" ] + "Abbreviations": ["J/(mol*K)"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/MolarMass.json b/Common/UnitDefinitions/MolarMass.json index 1d9e82c49c..94fd79c2a3 100644 --- a/Common/UnitDefinitions/MolarMass.json +++ b/Common/UnitDefinitions/MolarMass.json @@ -1,7 +1,8 @@ { "Name": "MolarMass", "BaseUnit": "KilogramPerMole", - "XmlDoc": "In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance.", + "XmlDoc": + "In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance.", "BaseDimensions": { "M": 1, "N": -1 @@ -12,15 +13,15 @@ "PluralName": "GramsPerMole", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "g/mol" ] + "Abbreviations": ["g/mol"] }, { "Culture": "ru-RU", - "Abbreviations": [ "г/моль" ] + "Abbreviations": ["г/моль"] } ] }, @@ -29,17 +30,17 @@ "PluralName": "PoundsPerMole", "FromUnitToBaseFunc": "x*0.45359237", "FromBaseToUnitFunc": "x/0.45359237", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/mol" ] + "Abbreviations": ["lb/mol"] }, { "Culture": "ru-RU", - "Abbreviations": [ "фунт/моль" ] + "Abbreviations": ["фунт/моль"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/Molarity.json b/Common/UnitDefinitions/Molarity.json index 30a55110e0..0a78e12494 100644 --- a/Common/UnitDefinitions/Molarity.json +++ b/Common/UnitDefinitions/Molarity.json @@ -1,7 +1,8 @@ { "Name": "Molarity", "BaseUnit": "MolesPerCubicMeter", - "XmlDoc": "Molar concentration, also called molarity, amount concentration or substance concentration, is a measure of the concentration of a solute in a solution, or of any chemical species, in terms of amount of substance in a given volume. ", + "XmlDoc": + "Molar concentration, also called molarity, amount concentration or substance concentration, is a measure of the concentration of a solute in a solution, or of any chemical species, in terms of amount of substance in a given volume. ", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Molar_concentration", "BaseDimensions": { "L": -3, @@ -21,7 +22,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mol/m³" ] + "Abbreviations": ["mol/m³"] } ] }, @@ -34,13 +35,13 @@ }, "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mol/L", "M"] + "Abbreviations": ["mol/L", "M"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/Permeability.json b/Common/UnitDefinitions/Permeability.json index 8f020ec80f..829d8baec0 100644 --- a/Common/UnitDefinitions/Permeability.json +++ b/Common/UnitDefinitions/Permeability.json @@ -1,7 +1,8 @@ { "Name": "Permeability", "BaseUnit": "HenryPerMeter", - "XmlDoc": "In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself.", + "XmlDoc": + "In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Permeability_(electromagnetism)", "BaseDimensions": { "L": 1, @@ -18,7 +19,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "H/m" ] + "Abbreviations": ["H/m"] } ] } diff --git a/Common/UnitDefinitions/Permittivity.json b/Common/UnitDefinitions/Permittivity.json index 9ca8109e42..fda4c32d63 100644 --- a/Common/UnitDefinitions/Permittivity.json +++ b/Common/UnitDefinitions/Permittivity.json @@ -1,7 +1,8 @@ { "Name": "Permittivity", "BaseUnit": "FaradPerMeter", - "XmlDoc": "In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium.", + "XmlDoc": + "In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Permittivity", "BaseDimensions": { "L": -3, @@ -18,7 +19,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "F/m" ] + "Abbreviations": ["F/m"] } ] } diff --git a/Common/UnitDefinitions/Power.json b/Common/UnitDefinitions/Power.json index 1ac546dbf1..73d27233aa 100644 --- a/Common/UnitDefinitions/Power.json +++ b/Common/UnitDefinitions/Power.json @@ -2,7 +2,8 @@ "Name": "Power", "BaseUnit": "Watt", "BaseType": "decimal", - "XmlDoc": "In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time.", + "XmlDoc": + "In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time.", "BaseDimensions": { "L": 2, "M": 1, @@ -14,11 +15,11 @@ "PluralName": "Watts", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Femto", "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera", "Peta" ], + "Prefixes": ["Femto", "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera", "Peta"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W" ] + "Abbreviations": ["W"] } ] }, @@ -30,7 +31,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "hp(I)" ] + "Abbreviations": ["hp(I)"] } ] }, @@ -42,7 +43,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "hp(M)" ] + "Abbreviations": ["hp(M)"] } ] }, @@ -54,7 +55,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "hp(E)" ] + "Abbreviations": ["hp(E)"] } ] }, @@ -66,7 +67,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "hp(S)" ] + "Abbreviations": ["hp(S)"] } ] }, @@ -78,7 +79,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "hp(H)" ] + "Abbreviations": ["hp(H)"] } ] }, @@ -87,11 +88,11 @@ "PluralName": "BritishThermalUnitsPerHour", "FromUnitToBaseFunc": "x*0.293071m", "FromBaseToUnitFunc": "x/0.293071m", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Btu/h", "Btu/hr" ] + "Abbreviations": ["Btu/h", "Btu/hr"] } ] }, @@ -100,11 +101,11 @@ "PluralName": "JoulesPerHour", "FromUnitToBaseFunc": "x/3600m", "FromBaseToUnitFunc": "x*3600m", - "Prefixes": [ "Milli", "Kilo", "Mega", "Giga" ], + "Prefixes": ["Milli", "Kilo", "Mega", "Giga"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/h" ] + "Abbreviations": ["J/h"] } ] }, diff --git a/Common/UnitDefinitions/PowerDensity.json b/Common/UnitDefinitions/PowerDensity.json index 137b03aa1e..93f4ae4866 100644 --- a/Common/UnitDefinitions/PowerDensity.json +++ b/Common/UnitDefinitions/PowerDensity.json @@ -18,11 +18,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/m³" ] + "Abbreviations": ["W/m³"] } ] }, @@ -31,11 +31,11 @@ "PluralName": "WattsPerCubicInch", "FromUnitToBaseFunc": "x*6.102374409473228e4", "FromBaseToUnitFunc": "x/6.102374409473228e4", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/in³" ] + "Abbreviations": ["W/in³"] } ] }, @@ -44,11 +44,11 @@ "PluralName": "WattsPerCubicFoot", "FromUnitToBaseFunc": "x*3.531466672148859e1", "FromBaseToUnitFunc": "x/3.531466672148859e1", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/ft³" ] + "Abbreviations": ["W/ft³"] } ] }, @@ -57,11 +57,11 @@ "PluralName": "WattsPerLiter", "FromUnitToBaseFunc": "x*1.0e3", "FromBaseToUnitFunc": "x/1.0e3", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/l" ] + "Abbreviations": ["W/l"] } ] } diff --git a/Common/UnitDefinitions/PowerRatio.json b/Common/UnitDefinitions/PowerRatio.json index 1a0bf26e9f..68722aeb76 100644 --- a/Common/UnitDefinitions/PowerRatio.json +++ b/Common/UnitDefinitions/PowerRatio.json @@ -13,7 +13,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dBW" ] + "Abbreviations": ["dBW"] } ] }, @@ -25,7 +25,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dBmW", "dBm" ] + "Abbreviations": ["dBmW", "dBm"] } ] } diff --git a/Common/UnitDefinitions/Pressure.json b/Common/UnitDefinitions/Pressure.json index a58487f142..2369eca3d0 100644 --- a/Common/UnitDefinitions/Pressure.json +++ b/Common/UnitDefinitions/Pressure.json @@ -1,7 +1,8 @@ { "Name": "Pressure", "BaseUnit": "Pascal", - "XmlDoc": "Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa).", + "XmlDoc": + "Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa).", "BaseDimensions": { "L": -1, "M": 1, @@ -18,15 +19,15 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Micro", "Milli", "Deca", "Hecto", "Kilo", "Mega", "Giga" ], + "Prefixes": ["Micro", "Milli", "Deca", "Hecto", "Kilo", "Mega", "Giga"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Pa" ] + "Abbreviations": ["Pa"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Па" ] + "Abbreviations": ["Па"] } ] }, @@ -38,11 +39,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "atm" ] + "Abbreviations": ["atm"] }, { "Culture": "ru-RU", - "Abbreviations": [ "атм" ] + "Abbreviations": ["атм"] } ] }, @@ -51,15 +52,15 @@ "PluralName": "Bars", "FromUnitToBaseFunc": "x*1e5", "FromBaseToUnitFunc": "x/1e5", - "Prefixes": [ "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega" ], + "Prefixes": ["Micro", "Milli", "Centi", "Deci", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bar" ] + "Abbreviations": ["bar"] }, { "Culture": "ru-RU", - "Abbreviations": [ "бар" ] + "Abbreviations": ["бар"] } ] }, @@ -71,11 +72,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf/m²" ] + "Abbreviations": ["kgf/m²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "кгс/м²" ] + "Abbreviations": ["кгс/м²"] } ] }, @@ -87,11 +88,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf/cm²" ] + "Abbreviations": ["kgf/cm²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "кгс/см²" ] + "Abbreviations": ["кгс/см²"] } ] }, @@ -103,11 +104,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf/mm²" ] + "Abbreviations": ["kgf/mm²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "кгс/мм²" ] + "Abbreviations": ["кгс/мм²"] } ] }, @@ -116,15 +117,15 @@ "PluralName": "NewtonsPerSquareMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N/m²" ] + "Abbreviations": ["N/m²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Н/м²" ] + "Abbreviations": ["Н/м²"] } ] }, @@ -133,15 +134,15 @@ "PluralName": "NewtonsPerSquareCentimeter", "FromUnitToBaseFunc": "x*1e4", "FromBaseToUnitFunc": "x/1e4", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N/cm²" ] + "Abbreviations": ["N/cm²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Н/см²" ] + "Abbreviations": ["Н/см²"] } ] }, @@ -150,15 +151,15 @@ "PluralName": "NewtonsPerSquareMillimeter", "FromUnitToBaseFunc": "x*1e6", "FromBaseToUnitFunc": "x/1e6", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N/mm²" ] + "Abbreviations": ["N/mm²"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Н/мм²" ] + "Abbreviations": ["Н/мм²"] } ] }, @@ -170,11 +171,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "at" ] + "Abbreviations": ["at"] }, { "Culture": "ru-RU", - "Abbreviations": [ "ат" ] + "Abbreviations": ["ат"] } ] }, @@ -186,11 +187,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "torr" ] + "Abbreviations": ["torr"] }, { "Culture": "ru-RU", - "Abbreviations": [ "торр" ] + "Abbreviations": ["торр"] } ] }, @@ -199,11 +200,11 @@ "PluralName": "PoundsForcePerSquareInch", "FromUnitToBaseFunc": "x*6.894757293168361e3", "FromBaseToUnitFunc": "x/6.894757293168361e3", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "psi", "lb/in²" ], + "Abbreviations": ["psi", "lb/in²"], "AbbreviationsForPrefixes": { "Kilo": "kipf/in²" } } ] @@ -213,11 +214,11 @@ "PluralName": "PoundsForcePerSquareFoot", "FromUnitToBaseFunc": "x*4.788025898033584e1", "FromBaseToUnitFunc": "x/4.788025898033584e1", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lb/ft²" ], + "Abbreviations": ["lb/ft²"], "AbbreviationsForPrefixes": { "Kilo": "kipf/ft²" } } ] @@ -230,7 +231,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf/mm²" ] + "Abbreviations": ["tf/mm²"] } ] }, @@ -242,7 +243,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf/m²" ] + "Abbreviations": ["tf/m²"] } ] }, @@ -254,7 +255,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m of head" ] + "Abbreviations": ["m of head"] } ] }, @@ -266,7 +267,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf/cm²" ] + "Abbreviations": ["tf/cm²"] } ] }, @@ -278,7 +279,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft of head" ] + "Abbreviations": ["ft of head"] } ] }, @@ -290,7 +291,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mmHg" ] + "Abbreviations": ["mmHg"] } ] }, @@ -302,7 +303,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "inHg" ] + "Abbreviations": ["inHg"] } ] }, @@ -314,7 +315,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dyn/cm²" ] + "Abbreviations": ["dyn/cm²"] } ] }, @@ -326,7 +327,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbm/(in·s²)", "lb/(in·s²)" ] + "Abbreviations": ["lbm/(in·s²)", "lb/(in·s²)"] } ] }, @@ -338,9 +339,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "wc" ] + "Abbreviations": ["wc"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/PressureChangeRate.json b/Common/UnitDefinitions/PressureChangeRate.json index 14d7f017bc..8cc9066f17 100644 --- a/Common/UnitDefinitions/PressureChangeRate.json +++ b/Common/UnitDefinitions/PressureChangeRate.json @@ -1,7 +1,8 @@ { "Name": "PressureChangeRate", "BaseUnit": "PascalPerSecond", - "XmlDoc": "Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time).", + "XmlDoc": + "Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time).", "BaseDimensions": { "L": -1, "M": 1, @@ -13,15 +14,15 @@ "PluralName": "PascalsPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Pa/s" ] + "Abbreviations": ["Pa/s"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Па/с" ] + "Abbreviations": ["Па/с"] } ] }, @@ -30,15 +31,15 @@ "PluralName": "PascalsPerMinute", "FromUnitToBaseFunc": "x/60", "FromBaseToUnitFunc": "x*60", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Pa/min" ] + "Abbreviations": ["Pa/min"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Па/с" ] + "Abbreviations": ["Па/с"] } ] }, @@ -50,13 +51,13 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "atm/s" ] + "Abbreviations": ["atm/s"] }, { "Culture": "ru-RU", - "Abbreviations": [ "атм/с" ] + "Abbreviations": ["атм/с"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/Ratio.json b/Common/UnitDefinitions/Ratio.json index c9387a5397..d2ff8e955b 100644 --- a/Common/UnitDefinitions/Ratio.json +++ b/Common/UnitDefinitions/Ratio.json @@ -1,7 +1,8 @@ { "Name": "Ratio", "BaseUnit": "DecimalFraction", - "XmlDoc": "In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as \"a to b\" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer).", + "XmlDoc": + "In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as \"a to b\" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer).", "Units": [ { "SingularName": "DecimalFraction", @@ -11,7 +12,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "" ] + "Abbreviations": [""] } ] }, @@ -23,7 +24,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "%" ] + "Abbreviations": ["%"] } ] }, @@ -35,7 +36,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "‰" ] + "Abbreviations": ["‰"] } ] }, @@ -47,7 +48,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppm" ] + "Abbreviations": ["ppm"] } ] }, @@ -59,7 +60,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppb" ] + "Abbreviations": ["ppb"] } ] }, @@ -71,7 +72,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppt" ] + "Abbreviations": ["ppt"] } ] } diff --git a/Common/UnitDefinitions/RatioChangeRate.json b/Common/UnitDefinitions/RatioChangeRate.json index 019bd89419..554ac130d1 100644 --- a/Common/UnitDefinitions/RatioChangeRate.json +++ b/Common/UnitDefinitions/RatioChangeRate.json @@ -11,7 +11,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "%/s" ] + "Abbreviations": ["%/s"] } ] }, @@ -23,10 +23,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "/s" ] + "Abbreviations": ["/s"] } ] } - ] } \ No newline at end of file diff --git a/Common/UnitDefinitions/ReactiveEnergy.json b/Common/UnitDefinitions/ReactiveEnergy.json index 9ac64f67d4..f10dd51b34 100644 --- a/Common/UnitDefinitions/ReactiveEnergy.json +++ b/Common/UnitDefinitions/ReactiveEnergy.json @@ -1,7 +1,8 @@ { "Name": "ReactiveEnergy", "BaseUnit": "VoltampereReactiveHour", - "XmlDoc": "The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour.", + "XmlDoc": + "The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour.", "BaseDimensions": { "L": 2, "M": 1, @@ -13,11 +14,11 @@ "PluralName": "VoltampereReactiveHours", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "varh" ] + "Abbreviations": ["varh"] } ] } diff --git a/Common/UnitDefinitions/ReactivePower.json b/Common/UnitDefinitions/ReactivePower.json index e02d22fe96..390530c770 100644 --- a/Common/UnitDefinitions/ReactivePower.json +++ b/Common/UnitDefinitions/ReactivePower.json @@ -1,7 +1,8 @@ { "Name": "ReactivePower", "BaseUnit": "VoltampereReactive", - "XmlDoc": "Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase.", + "XmlDoc": + "Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase.", "BaseDimensions": { "L": 2, "M": 1, @@ -13,11 +14,11 @@ "PluralName": "VoltamperesReactive", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega", "Giga" ], + "Prefixes": ["Kilo", "Mega", "Giga"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "var" ] + "Abbreviations": ["var"] } ] } diff --git a/Common/UnitDefinitions/RotationalAcceleration.json b/Common/UnitDefinitions/RotationalAcceleration.json index 78d28c1622..8132039484 100644 --- a/Common/UnitDefinitions/RotationalAcceleration.json +++ b/Common/UnitDefinitions/RotationalAcceleration.json @@ -14,7 +14,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "rad/s²" ] + "Abbreviations": ["rad/s²"] } ] }, @@ -26,7 +26,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°/s²", "deg/s²" ] + "Abbreviations": ["°/s²", "deg/s²"] } ] }, @@ -38,7 +38,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "rpm/s" ] + "Abbreviations": ["rpm/s"] } ] }, @@ -50,7 +50,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "r/s²" ] + "Abbreviations": ["r/s²"] } ] } diff --git a/Common/UnitDefinitions/RotationalSpeed.json b/Common/UnitDefinitions/RotationalSpeed.json index 66c5bd8195..2d33d11290 100644 --- a/Common/UnitDefinitions/RotationalSpeed.json +++ b/Common/UnitDefinitions/RotationalSpeed.json @@ -1,7 +1,8 @@ { "Name": "RotationalSpeed", "BaseUnit": "RadianPerSecond", - "XmlDoc": "Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter \"omega\").", + "XmlDoc": + "Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter \"omega\").", "BaseDimensions": { "T": -1 }, @@ -11,15 +12,15 @@ "PluralName": "RadiansPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "rad/s" ] + "Abbreviations": ["rad/s"] }, { "Culture": "ru-RU", - "Abbreviations": [ "рад/с" ] + "Abbreviations": ["рад/с"] } ] }, @@ -28,15 +29,15 @@ "PluralName": "DegreesPerSecond", "FromUnitToBaseFunc": "(Math.PI/180)*x", "FromBaseToUnitFunc": "(180/Math.PI)*x", - "Prefixes": [ "Nano", "Micro", "Milli" ], + "Prefixes": ["Nano", "Micro", "Milli"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°/s", "deg/s" ] + "Abbreviations": ["°/s", "deg/s"] }, { "Culture": "ru-RU", - "Abbreviations": [ "°/с" ] + "Abbreviations": ["°/с"] } ] }, @@ -48,7 +49,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°/min", "deg/min" ] + "Abbreviations": ["°/min", "deg/min"] } ] }, @@ -60,11 +61,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "r/s" ] + "Abbreviations": ["r/s"] }, { "Culture": "ru-RU", - "Abbreviations": [ "об/с" ] + "Abbreviations": ["об/с"] } ] }, @@ -76,11 +77,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "rpm", "r/min" ] + "Abbreviations": ["rpm", "r/min"] }, { "Culture": "ru-RU", - "Abbreviations": [ "об/мин" ] + "Abbreviations": ["об/мин"] } ] } diff --git a/Common/UnitDefinitions/RotationalStiffness.json b/Common/UnitDefinitions/RotationalStiffness.json index 59b9afd6fa..e997cb1139 100644 --- a/Common/UnitDefinitions/RotationalStiffness.json +++ b/Common/UnitDefinitions/RotationalStiffness.json @@ -13,11 +13,11 @@ "PluralName": "NewtonMetersPerRadian", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N·m/rad", "Nm/rad" ] + "Abbreviations": ["N·m/rad", "Nm/rad"] } ] } diff --git a/Common/UnitDefinitions/RotationalStiffnessPerLength.json b/Common/UnitDefinitions/RotationalStiffnessPerLength.json index 2135137175..ec46b3dafb 100644 --- a/Common/UnitDefinitions/RotationalStiffnessPerLength.json +++ b/Common/UnitDefinitions/RotationalStiffnessPerLength.json @@ -13,11 +13,11 @@ "PluralName": "NewtonMetersPerRadianPerMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N·m/rad/m", "Nm/rad/m" ] + "Abbreviations": ["N·m/rad/m", "Nm/rad/m"] } ] } diff --git a/Common/UnitDefinitions/SolidAngle.json b/Common/UnitDefinitions/SolidAngle.json index 10cced6eee..ecc6f245bf 100644 --- a/Common/UnitDefinitions/SolidAngle.json +++ b/Common/UnitDefinitions/SolidAngle.json @@ -1,7 +1,8 @@ { "Name": "SolidAngle", "BaseUnit": "Steradian", - "XmlDoc": "In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point.", + "XmlDoc": + "In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Solid_angle", "Units": [ { @@ -12,7 +13,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "sr" ] + "Abbreviations": ["sr"] } ] } diff --git a/Common/UnitDefinitions/SpecificEnergy.json b/Common/UnitDefinitions/SpecificEnergy.json index 8c706f0b83..030864f872 100644 --- a/Common/UnitDefinitions/SpecificEnergy.json +++ b/Common/UnitDefinitions/SpecificEnergy.json @@ -13,11 +13,11 @@ "PluralName": "JoulesPerKilogram", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/kg" ] + "Abbreviations": ["J/kg"] } ] }, @@ -26,11 +26,11 @@ "PluralName": "CaloriesPerGram", "FromUnitToBaseFunc": "x*4.184e3", "FromBaseToUnitFunc": "x/4.184e3", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cal/g" ] + "Abbreviations": ["cal/g"] } ] }, @@ -39,11 +39,11 @@ "PluralName": "WattHoursPerKilogram", "FromUnitToBaseFunc": "x*3.6e3", "FromBaseToUnitFunc": "x/3.6e3", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Wh/kg" ] + "Abbreviations": ["Wh/kg"] } ] }, @@ -55,10 +55,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "btu/lb" ] + "Abbreviations": ["btu/lb"] } ] } - ] } \ No newline at end of file diff --git a/Common/UnitDefinitions/SpecificEntropy.json b/Common/UnitDefinitions/SpecificEntropy.json index 4bfeac565a..1bdb75379a 100644 --- a/Common/UnitDefinitions/SpecificEntropy.json +++ b/Common/UnitDefinitions/SpecificEntropy.json @@ -1,7 +1,8 @@ { "Name": "SpecificEntropy", "BaseUnit": "JoulePerKilogramKelvin", - "XmlDoc": "Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass.", + "XmlDoc": + "Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass.", "BaseDimensions": { "L": 2, "T": -2, @@ -13,11 +14,11 @@ "PluralName": "JoulesPerKilogramKelvin", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/kg.K" ] + "Abbreviations": ["J/kg.K"] } ] }, @@ -26,11 +27,11 @@ "PluralName": "JoulesPerKilogramDegreeCelsius", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "J/kg.C" ] + "Abbreviations": ["J/kg.C"] } ] }, @@ -39,11 +40,11 @@ "PluralName": "CaloriesPerGramKelvin", "FromUnitToBaseFunc": "x*4.184e3", "FromBaseToUnitFunc": "x/4.184e3", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cal/g.K" ] + "Abbreviations": ["cal/g.K"] } ] }, @@ -55,7 +56,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "BTU/lb·°F", "BTU/lbm·°F" ] + "Abbreviations": ["BTU/lb·°F", "BTU/lbm·°F"] } ] } diff --git a/Common/UnitDefinitions/SpecificVolume.json b/Common/UnitDefinitions/SpecificVolume.json index 9a6d3a2083..c977e4dd7b 100644 --- a/Common/UnitDefinitions/SpecificVolume.json +++ b/Common/UnitDefinitions/SpecificVolume.json @@ -1,7 +1,8 @@ { "Name": "SpecificVolume", "BaseUnit": "CubicMeterPerKilogram", - "XmlDoc": "In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well.", + "XmlDoc": + "In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well.", "BaseDimensions": { "L": 3, "M": -1 @@ -12,11 +13,11 @@ "PluralName": "CubicMetersPerKilogram", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Milli" ], + "Prefixes": ["Milli"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m³/kg" ] + "Abbreviations": ["m³/kg"] } ] }, @@ -29,9 +30,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft³/lb" ] + "Abbreviations": ["ft³/lb"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/SpecificWeight.json b/Common/UnitDefinitions/SpecificWeight.json index 5ffecf2923..49edec6f7c 100644 --- a/Common/UnitDefinitions/SpecificWeight.json +++ b/Common/UnitDefinitions/SpecificWeight.json @@ -1,7 +1,8 @@ { "Name": "SpecificWeight", "BaseUnit": "NewtonPerCubicMeter", - "XmlDoc": "The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume.", + "XmlDoc": + "The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Specificweight", "BaseDimensions": { "L": -2, @@ -14,11 +15,11 @@ "PluralName": "NewtonsPerCubicMillimeter", "FromUnitToBaseFunc": "x*1000000000", "FromBaseToUnitFunc": "x*0.000000001", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N/mm³" ] + "Abbreviations": ["N/mm³"] } ] }, @@ -27,11 +28,11 @@ "PluralName": "NewtonsPerCubicCentimeter", "FromUnitToBaseFunc": "x*1000000", "FromBaseToUnitFunc": "x*0.000001", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N/cm³" ] + "Abbreviations": ["N/cm³"] } ] }, @@ -40,11 +41,11 @@ "PluralName": "NewtonsPerCubicMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N/m³" ] + "Abbreviations": ["N/m³"] } ] }, @@ -56,7 +57,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf/mm³" ] + "Abbreviations": ["kgf/mm³"] } ] }, @@ -68,7 +69,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf/cm³" ] + "Abbreviations": ["kgf/cm³"] } ] }, @@ -80,7 +81,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf/m³" ] + "Abbreviations": ["kgf/m³"] } ] }, @@ -89,11 +90,11 @@ "PluralName": "PoundsForcePerCubicInch", "FromUnitToBaseFunc": "x*2.714471375263134e5", "FromBaseToUnitFunc": "x/2.714471375263134e5", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf/in³" ], + "Abbreviations": ["lbf/in³"], "AbbreviationsForPrefixes": { "Kilo": "kipf/in³" } } ] @@ -103,11 +104,11 @@ "PluralName": "PoundsForcePerCubicFoot", "FromUnitToBaseFunc": "x*1.570874638462462e2", "FromBaseToUnitFunc": "x/1.570874638462462e2", - "Prefixes": [ "Kilo" ], + "Prefixes": ["Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf/ft³" ], + "Abbreviations": ["lbf/ft³"], "AbbreviationsForPrefixes": { "Kilo": "kipf/ft³" } } ] @@ -120,7 +121,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf/mm³" ] + "Abbreviations": ["tf/mm³"] } ] }, @@ -132,7 +133,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf/cm³" ] + "Abbreviations": ["tf/cm³"] } ] }, @@ -144,9 +145,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf/m³" ] + "Abbreviations": ["tf/m³"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/Speed.json b/Common/UnitDefinitions/Speed.json index f912c81946..7fd65b7d75 100644 --- a/Common/UnitDefinitions/Speed.json +++ b/Common/UnitDefinitions/Speed.json @@ -1,7 +1,8 @@ { "Name": "Speed", "BaseUnit": "MeterPerSecond", - "XmlDoc": "In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero.", + "XmlDoc": + "In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero.", "BaseDimensions": { "L": 1, "T": -1 @@ -16,11 +17,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m/s" ] + "Abbreviations": ["m/s"] } ] }, @@ -33,11 +34,11 @@ }, "FromUnitToBaseFunc": "x/60", "FromBaseToUnitFunc": "x*60", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m/min" ] + "Abbreviations": ["m/min"] } ] }, @@ -50,11 +51,11 @@ }, "FromUnitToBaseFunc": "x/3600", "FromBaseToUnitFunc": "x*3600", - "Prefixes": [ "Milli", "Centi", "Kilo" ], + "Prefixes": ["Milli", "Centi", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m/h" ] + "Abbreviations": ["m/h"] } ] }, @@ -70,7 +71,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft/s" ] + "Abbreviations": ["ft/s"] } ] }, @@ -86,7 +87,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft/min" ] + "Abbreviations": ["ft/min"] } ] }, @@ -102,7 +103,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft/h" ] + "Abbreviations": ["ft/h"] } ] }, @@ -118,7 +119,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ftUS/s" ] + "Abbreviations": ["ftUS/s"] } ] }, @@ -134,7 +135,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ftUS/min" ] + "Abbreviations": ["ftUS/min"] } ] }, @@ -150,7 +151,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ftUS/h" ] + "Abbreviations": ["ftUS/h"] } ] }, @@ -166,7 +167,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "in/s" ] + "Abbreviations": ["in/s"] } ] }, @@ -182,7 +183,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "in/min" ] + "Abbreviations": ["in/min"] } ] }, @@ -198,7 +199,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "in/h" ] + "Abbreviations": ["in/h"] } ] }, @@ -214,7 +215,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "yd/s" ] + "Abbreviations": ["yd/s"] } ] }, @@ -230,7 +231,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "yd/min" ] + "Abbreviations": ["yd/min"] } ] }, @@ -246,7 +247,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "yd/h" ] + "Abbreviations": ["yd/h"] } ] }, @@ -262,7 +263,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kn", "kt", "knot", "knots" ] + "Abbreviations": ["kn", "kt", "knot", "knots"] } ] }, @@ -278,7 +279,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mph" ] + "Abbreviations": ["mph"] } ] } diff --git a/Common/UnitDefinitions/Temperature.json b/Common/UnitDefinitions/Temperature.json index 15a87bdc4f..5c3795609d 100644 --- a/Common/UnitDefinitions/Temperature.json +++ b/Common/UnitDefinitions/Temperature.json @@ -1,7 +1,8 @@ { "Name": "Temperature", "BaseUnit": "Kelvin", - "XmlDoc": "A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics.", + "XmlDoc": + "A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics.", "GenerateArithmetic": false, "BaseDimensions": { "Θ": 1 @@ -18,7 +19,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "K" ] + "Abbreviations": ["K"] } ] }, @@ -33,7 +34,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°C" ] + "Abbreviations": ["°C"] } ] }, @@ -48,7 +49,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°De" ] + "Abbreviations": ["°De"] } ] }, @@ -63,7 +64,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°F" ] + "Abbreviations": ["°F"] } ] }, @@ -78,7 +79,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°N" ] + "Abbreviations": ["°N"] } ] }, @@ -93,7 +94,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°R" ] + "Abbreviations": ["°R"] } ] }, @@ -108,7 +109,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°Ré" ] + "Abbreviations": ["°Ré"] } ] }, @@ -123,7 +124,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°Rø" ] + "Abbreviations": ["°Rø"] } ] }, @@ -135,7 +136,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "T⊙" ] + "Abbreviations": ["T⊙"] } ] } diff --git a/Common/UnitDefinitions/TemperatureChangeRate.json b/Common/UnitDefinitions/TemperatureChangeRate.json index 4d08f7b5dd..9bd33a1d9d 100644 --- a/Common/UnitDefinitions/TemperatureChangeRate.json +++ b/Common/UnitDefinitions/TemperatureChangeRate.json @@ -1,7 +1,8 @@ { "Name": "TemperatureChangeRate", "BaseUnit": "DegreeCelsiusPerSecond", - "XmlDoc": "Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time).", + "XmlDoc": + "Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time).", "BaseDimensions": { "T": -1, "Θ": 1 @@ -12,11 +13,11 @@ "PluralName": "DegreesCelsiusPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°C/s" ] + "Abbreviations": ["°C/s"] } ] }, @@ -28,7 +29,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "°C/min" ] + "Abbreviations": ["°C/min"] } ] } diff --git a/Common/UnitDefinitions/TemperatureDelta.json b/Common/UnitDefinitions/TemperatureDelta.json index 34b37da1ea..b07dfec64c 100644 --- a/Common/UnitDefinitions/TemperatureDelta.json +++ b/Common/UnitDefinitions/TemperatureDelta.json @@ -11,7 +11,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "∆K" ] + "Abbreviations": ["∆K"] } ] }, @@ -23,7 +23,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "∆°C" ] + "Abbreviations": ["∆°C"] } ] }, @@ -35,7 +35,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "∆°De" ] + "Abbreviations": ["∆°De"] } ] }, @@ -47,7 +47,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "∆°F" ] + "Abbreviations": ["∆°F"] } ] }, @@ -59,7 +59,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "∆°N" ] + "Abbreviations": ["∆°N"] } ] }, @@ -71,7 +71,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "∆°R" ] + "Abbreviations": ["∆°R"] } ] }, @@ -83,7 +83,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "∆°Ré" ] + "Abbreviations": ["∆°Ré"] } ] }, @@ -95,7 +95,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "∆°Rø" ] + "Abbreviations": ["∆°Rø"] } ] } diff --git a/Common/UnitDefinitions/ThermalConductivity.json b/Common/UnitDefinitions/ThermalConductivity.json index 67afec23b4..0aefcee915 100644 --- a/Common/UnitDefinitions/ThermalConductivity.json +++ b/Common/UnitDefinitions/ThermalConductivity.json @@ -18,7 +18,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "W/m·K" ] + "Abbreviations": ["W/m·K"] } ] }, @@ -30,7 +30,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "BTU/h·ft·°F" ] + "Abbreviations": ["BTU/h·ft·°F"] } ] } diff --git a/Common/UnitDefinitions/ThermalResistance.json b/Common/UnitDefinitions/ThermalResistance.json index c5fc7d8415..21292d4383 100644 --- a/Common/UnitDefinitions/ThermalResistance.json +++ b/Common/UnitDefinitions/ThermalResistance.json @@ -16,7 +16,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m²K/kW" ] + "Abbreviations": ["m²K/kW"] } ] }, @@ -28,7 +28,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m²°C/W" ] + "Abbreviations": ["m²°C/W"] } ] }, @@ -40,7 +40,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cm²K/W" ] + "Abbreviations": ["cm²K/W"] } ] }, @@ -52,7 +52,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cm²Hr°C/kcal" ] + "Abbreviations": ["cm²Hr°C/kcal"] } ] }, @@ -64,10 +64,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "Hrft²°F/Btu" ] + "Abbreviations": ["Hrft²°F/Btu"] } ] } - ] } \ No newline at end of file diff --git a/Common/UnitDefinitions/Torque.json b/Common/UnitDefinitions/Torque.json index 90e8a26d45..29a5f1dc94 100644 --- a/Common/UnitDefinitions/Torque.json +++ b/Common/UnitDefinitions/Torque.json @@ -1,7 +1,8 @@ { "Name": "Torque", "BaseUnit": "NewtonMeter", - "XmlDoc": "Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt.", + "XmlDoc": + "Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt.", "BaseDimensions": { "L": 2, "M": 1, @@ -13,11 +14,11 @@ "PluralName": "NewtonMillimeters", "FromUnitToBaseFunc": "x*0.001", "FromBaseToUnitFunc": "x*1000", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N·mm" ] + "Abbreviations": ["N·mm"] } ] }, @@ -26,11 +27,11 @@ "PluralName": "NewtonCentimeters", "FromUnitToBaseFunc": "x*0.01", "FromBaseToUnitFunc": "x*100", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N·cm" ] + "Abbreviations": ["N·cm"] } ] }, @@ -39,15 +40,15 @@ "PluralName": "NewtonMeters", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N·m" ] + "Abbreviations": ["N·m"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Н·м" ] + "Abbreviations": ["Н·м"] } ] }, @@ -56,11 +57,11 @@ "PluralName": "PoundForceInches", "FromUnitToBaseFunc": "x*1.129848290276167e-1", "FromBaseToUnitFunc": "x/1.129848290276167e-1", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf·in" ], + "Abbreviations": ["lbf·in"], "AbbreviationsForPrefixes": { "Kilo": "kipf·in" } } ] @@ -70,11 +71,11 @@ "PluralName": "PoundForceFeet", "FromUnitToBaseFunc": "x*1.3558179483314", "FromBaseToUnitFunc": "x/1.3558179483314", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf·ft" ], + "Abbreviations": ["lbf·ft"], "AbbreviationsForPrefixes": { "Kilo": "kipf·ft" } } ] @@ -87,7 +88,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf·mm" ] + "Abbreviations": ["kgf·mm"] } ] }, @@ -99,7 +100,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf·cm" ] + "Abbreviations": ["kgf·cm"] } ] }, @@ -111,7 +112,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf·m" ] + "Abbreviations": ["kgf·m"] } ] }, @@ -123,7 +124,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf·mm" ] + "Abbreviations": ["tf·mm"] } ] }, @@ -135,7 +136,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf·cm" ] + "Abbreviations": ["tf·cm"] } ] }, @@ -147,9 +148,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf·m" ] + "Abbreviations": ["tf·m"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/TorquePerLength.json b/Common/UnitDefinitions/TorquePerLength.json index 9356721394..5656117ac0 100644 --- a/Common/UnitDefinitions/TorquePerLength.json +++ b/Common/UnitDefinitions/TorquePerLength.json @@ -13,11 +13,11 @@ "PluralName": "NewtonMillimetersPerMeter", "FromUnitToBaseFunc": "x*0.001", "FromBaseToUnitFunc": "x*1000", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N·mm/m" ] + "Abbreviations": ["N·mm/m"] } ] }, @@ -26,11 +26,11 @@ "PluralName": "NewtonCentimetersPerMeter", "FromUnitToBaseFunc": "x*0.01", "FromBaseToUnitFunc": "x*100", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N·cm/m" ] + "Abbreviations": ["N·cm/m"] } ] }, @@ -39,15 +39,15 @@ "PluralName": "NewtonMetersPerMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "N·m/m" ] + "Abbreviations": ["N·m/m"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Н·м/м" ] + "Abbreviations": ["Н·м/м"] } ] }, @@ -56,11 +56,11 @@ "PluralName": "PoundForceInchesPerFoot", "FromUnitToBaseFunc": "x*0.370685147638", "FromBaseToUnitFunc": "x/0.370685147638", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf·in/ft" ], + "Abbreviations": ["lbf·in/ft"], "AbbreviationsForPrefixes": { "Kilo": "kipf·in/ft" } } ] @@ -70,11 +70,11 @@ "PluralName": "PoundForceFeetPerFoot", "FromUnitToBaseFunc": "x*4.44822161526", "FromBaseToUnitFunc": "x/4.44822161526", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "lbf·ft/ft" ], + "Abbreviations": ["lbf·ft/ft"], "AbbreviationsForPrefixes": { "Kilo": "kipf·ft/ft" } } ] @@ -87,7 +87,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf·mm/m" ] + "Abbreviations": ["kgf·mm/m"] } ] }, @@ -99,7 +99,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf·cm/m" ] + "Abbreviations": ["kgf·cm/m"] } ] }, @@ -111,7 +111,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgf·m/m" ] + "Abbreviations": ["kgf·m/m"] } ] }, @@ -123,7 +123,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf·mm/m" ] + "Abbreviations": ["tf·mm/m"] } ] }, @@ -135,7 +135,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf·cm/m" ] + "Abbreviations": ["tf·cm/m"] } ] }, @@ -147,9 +147,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tf·m/m" ] + "Abbreviations": ["tf·m/m"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/VitaminA.json b/Common/UnitDefinitions/VitaminA.json index b503e93f3b..8e549febad 100644 --- a/Common/UnitDefinitions/VitaminA.json +++ b/Common/UnitDefinitions/VitaminA.json @@ -12,7 +12,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "IU" ] + "Abbreviations": ["IU"] } ] } diff --git a/Common/UnitDefinitions/Volume.json b/Common/UnitDefinitions/Volume.json index d2e87ac4b2..1098516672 100644 --- a/Common/UnitDefinitions/Volume.json +++ b/Common/UnitDefinitions/Volume.json @@ -1,7 +1,8 @@ { "Name": "Volume", "BaseUnit": "CubicMeter", - "XmlDoc": "Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces.", + "XmlDoc": + "Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces.", "BaseDimensions": { "L": 3 }, @@ -11,15 +12,15 @@ "PluralName": "Liters", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": [ "Micro", "Milli", "Centi", "Deci", "Hecto", "Kilo", "Mega" ], + "Prefixes": ["Micro", "Milli", "Centi", "Deci", "Hecto", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "l" ] + "Abbreviations": ["l"] }, { "Culture": "ru-RU", - "Abbreviations": [ "л" ] + "Abbreviations": ["л"] } ] }, @@ -28,15 +29,15 @@ "PluralName": "CubicMeters", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Hecto", "Kilo" ], + "Prefixes": ["Hecto", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m³" ] + "Abbreviations": ["m³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "м³" ] + "Abbreviations": ["м³"] } ] }, @@ -48,11 +49,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "km³" ] + "Abbreviations": ["km³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "км³" ] + "Abbreviations": ["км³"] } ] }, @@ -67,15 +68,15 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "hm³" ] + "Abbreviations": ["hm³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "гм³" ] + "Abbreviations": ["гм³"] } ] }, - { + { "SingularName": "CubicDecimeter", "PluralName": "CubicDecimeters", "FromUnitToBaseFunc": "x/1e3", @@ -83,11 +84,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dm³" ] + "Abbreviations": ["dm³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "дм³" ] + "Abbreviations": ["дм³"] } ] }, @@ -99,11 +100,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cm³" ] + "Abbreviations": ["cm³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "см³" ] + "Abbreviations": ["см³"] } ] }, @@ -115,11 +116,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mm³" ] + "Abbreviations": ["mm³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "мм³" ] + "Abbreviations": ["мм³"] } ] }, @@ -131,11 +132,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "µm³" ] + "Abbreviations": ["µm³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "мкм³" ] + "Abbreviations": ["мкм³"] } ] }, @@ -147,11 +148,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mi³" ] + "Abbreviations": ["mi³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "миля³" ] + "Abbreviations": ["миля³"] } ] }, @@ -163,11 +164,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "yd³" ] + "Abbreviations": ["yd³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "ярд³" ] + "Abbreviations": ["ярд³"] } ] }, @@ -176,15 +177,15 @@ "PluralName": "CubicFeet", "FromUnitToBaseFunc": "x*0.0283168", "FromBaseToUnitFunc": "x/0.0283168", - "Prefixes": [ "Hecto", "Kilo", "Mega" ], + "Prefixes": ["Hecto", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft³" ] + "Abbreviations": ["ft³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "фут³" ] + "Abbreviations": ["фут³"] } ] }, @@ -196,11 +197,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "in³" ] + "Abbreviations": ["in³"] }, { "Culture": "ru-RU", - "Abbreviations": [ "дюйм³" ] + "Abbreviations": ["дюйм³"] } ] }, @@ -209,15 +210,15 @@ "PluralName": "ImperialGallons", "FromUnitToBaseFunc": "x*0.00454609000000181429905810072407", "FromBaseToUnitFunc": "x/0.00454609000000181429905810072407", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gal (imp.)" ] + "Abbreviations": ["gal (imp.)"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Английский галлон" ] + "Abbreviations": ["Английский галлон"] } ] }, @@ -229,11 +230,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "oz (imp.)" ] + "Abbreviations": ["oz (imp.)"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Английская унция" ] + "Abbreviations": ["Английская унция"] } ] }, @@ -242,15 +243,15 @@ "PluralName": "UsGallons", "FromUnitToBaseFunc": "x*0.00378541", "FromBaseToUnitFunc": "x/0.00378541", - "Prefixes": [ "Kilo", "Mega" ], + "Prefixes": ["Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gal (U.S.)" ] + "Abbreviations": ["gal (U.S.)"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Американский галлон" ] + "Abbreviations": ["Американский галлон"] } ] }, @@ -262,11 +263,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "oz (U.S.)" ] + "Abbreviations": ["oz (U.S.)"] }, { "Culture": "ru-RU", - "Abbreviations": [ "Американская унция" ] + "Abbreviations": ["Американская унция"] } ] }, @@ -338,7 +339,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "tsp", "t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon" ] + "Abbreviations": ["tsp", "t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon"] }, { "Culture": "ru-RU", @@ -414,7 +415,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bbl" ] + "Abbreviations": ["bbl"] } ] }, @@ -426,7 +427,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bl (U.S.)" ] + "Abbreviations": ["bl (U.S.)"] } ] }, @@ -438,7 +439,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bl (imp.)" ] + "Abbreviations": ["bl (imp.)"] } ] }, @@ -450,7 +451,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "qt (U.S.)" ] + "Abbreviations": ["qt (U.S.)"] } ] }, @@ -462,7 +463,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "pt (U.S.)" ] + "Abbreviations": ["pt (U.S.)"] } ] }, @@ -474,7 +475,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ac-ft", "acre-foot", "acre-feet" ] + "Abbreviations": ["ac-ft", "acre-foot", "acre-feet"] } ] }, @@ -489,9 +490,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "pt (imp.)", "UK pt", "pt", "p" ] + "Abbreviations": ["pt (imp.)", "UK pt", "pt", "p"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/VolumeConcentration.json b/Common/UnitDefinitions/VolumeConcentration.json index de56f8491f..44ab1f85f0 100644 --- a/Common/UnitDefinitions/VolumeConcentration.json +++ b/Common/UnitDefinitions/VolumeConcentration.json @@ -1,10 +1,11 @@ { "Name": "VolumeConcentration", "BaseUnit": "DecimalFraction", - "XmlDoc": "The volume concentration (not to be confused with volume fraction) is defined as the volume of a constituent divided by the total volume of the mixture.", + "XmlDoc": + "The volume concentration (not to be confused with volume fraction) is defined as the volume of a constituent divided by the total volume of the mixture.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Concentration#Volume_concentration", "Units": [ - { + { "SingularName": "DecimalFraction", "PluralName": "DecimalFractions", "FromUnitToBaseFunc": "x", @@ -12,33 +13,33 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "" ] + "Abbreviations": [""] } ] }, - { + { "SingularName": "LitersPerLiter", "PluralName": "LitersPerLiter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "L/L" ] + "Abbreviations": ["L/L"] } ] }, - { + { "SingularName": "LitersPerMililiter", "PluralName": "LitersPerMililiter", "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], + "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "L/mL" ] + "Abbreviations": ["L/mL"] } ] }, @@ -50,7 +51,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "%", "% (v/v)" ] + "Abbreviations": ["%", "% (v/v)"] } ] }, @@ -62,7 +63,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "‰" ] + "Abbreviations": ["‰"] } ] }, @@ -74,7 +75,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppm" ] + "Abbreviations": ["ppm"] } ] }, @@ -86,7 +87,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppb" ] + "Abbreviations": ["ppb"] } ] }, @@ -98,7 +99,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ppt" ] + "Abbreviations": ["ppt"] } ] } diff --git a/Common/UnitDefinitions/VolumeFlow.json b/Common/UnitDefinitions/VolumeFlow.json index 6528c99c98..db5e20c620 100644 --- a/Common/UnitDefinitions/VolumeFlow.json +++ b/Common/UnitDefinitions/VolumeFlow.json @@ -1,7 +1,8 @@ { "Name": "VolumeFlow", "BaseUnit": "CubicMeterPerSecond", - "XmlDoc": "In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q.", + "XmlDoc": + "In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q.", "BaseDimensions": { "L": 3, "T": -1 @@ -15,11 +16,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m³/s" ] + "Abbreviations": ["m³/s"] }, { "Culture": "ru-RU", - "Abbreviations": [ "м³/с" ] + "Abbreviations": ["м³/с"] } ] }, @@ -31,7 +32,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m³/min" ] + "Abbreviations": ["m³/min"] } ] }, @@ -43,11 +44,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m³/h" ] + "Abbreviations": ["m³/h"] }, { "Culture": "ru-RU", - "Abbreviations": [ "м³/ч" ] + "Abbreviations": ["м³/ч"] } ] }, @@ -59,7 +60,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m³/d" ] + "Abbreviations": ["m³/d"] } ] }, @@ -71,7 +72,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft³/s" ] + "Abbreviations": ["ft³/s"] } ] }, @@ -83,7 +84,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft³/min" ] + "Abbreviations": ["ft³/min"] } ] }, @@ -95,7 +96,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "ft³/h", "cf/hr" ] + "Abbreviations": ["ft³/h", "cf/hr"] } ] }, @@ -107,7 +108,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "yd³/s" ] + "Abbreviations": ["yd³/s"] } ] }, @@ -119,7 +120,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "yd³/min" ] + "Abbreviations": ["yd³/min"] } ] }, @@ -131,7 +132,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "yd³/h" ] + "Abbreviations": ["yd³/h"] } ] }, @@ -143,7 +144,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "cy/day" ] + "Abbreviations": ["cy/day"] } ] }, @@ -155,7 +156,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "MGD" ] + "Abbreviations": ["MGD"] } ] }, @@ -167,7 +168,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gpd", "gal/d" ] + "Abbreviations": ["gpd", "gal/d"] } ] }, @@ -179,7 +180,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "L/s", "LPS" ] + "Abbreviations": ["L/s", "LPS"] } ] }, @@ -188,11 +189,11 @@ "PluralName": "LitersPerMinute", "FromUnitToBaseFunc": "x/60000.00000", "FromBaseToUnitFunc": "x*60000.00000", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "L/min", "LPM" ] + "Abbreviations": ["L/min", "LPM"] } ] }, @@ -204,11 +205,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "L/h", "LPH" ] + "Abbreviations": ["L/h", "LPH"] }, { "Culture": "ru-RU", - "Abbreviations": [ "л/ч" ] + "Abbreviations": ["л/ч"] } ] }, @@ -217,11 +218,11 @@ "PluralName": "LitersPerDay", "FromUnitToBaseFunc": "x/86400000", "FromBaseToUnitFunc": "x*86400000", - "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega" ], + "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "l/day", "L/d", "LPD" ] + "Abbreviations": ["l/day", "L/d", "LPD"] } ] }, @@ -233,7 +234,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gal (U.S.)/s" ] + "Abbreviations": ["gal (U.S.)/s"] } ] }, @@ -245,7 +246,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gal (U.S.)/min", "GPM" ] + "Abbreviations": ["gal (U.S.)/min", "GPM"] } ] }, @@ -257,7 +258,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gal (U. K.)/d" ] + "Abbreviations": ["gal (U. K.)/d"] } ] }, @@ -269,7 +270,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gal (imp.)/h" ] + "Abbreviations": ["gal (imp.)/h"] } ] }, @@ -281,7 +282,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gal (imp.)/min" ] + "Abbreviations": ["gal (imp.)/min"] } ] }, @@ -290,11 +291,11 @@ "PluralName": "UkGallonsPerSecond", "FromUnitToBaseFunc": "x/219.969", "FromBaseToUnitFunc": "x*219.969", - "Prefixes": [ "Mega" ], + "Prefixes": ["Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gal (imp.)/s" ] + "Abbreviations": ["gal (imp.)/s"] } ] }, @@ -306,7 +307,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "kgal (U.S.)/min", "KGPM" ] + "Abbreviations": ["kgal (U.S.)/min", "KGPM"] } ] }, @@ -318,7 +319,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "gal (U.S.)/h" ] + "Abbreviations": ["gal (U.S.)/h"] } ] }, @@ -330,11 +331,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "dm³/min" ] + "Abbreviations": ["dm³/min"] }, { "Culture": "ru-RU", - "Abbreviations": [ "дм³/мин" ] + "Abbreviations": ["дм³/мин"] } ] }, @@ -346,7 +347,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bbl/d", "BOPD" ] + "Abbreviations": ["bbl/d", "BOPD"] } ] }, @@ -358,7 +359,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bbl/min", "bpm" ] + "Abbreviations": ["bbl/min", "bpm"] } ] }, @@ -370,7 +371,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bbl/hr", "bph" ] + "Abbreviations": ["bbl/hr", "bph"] } ] }, @@ -382,7 +383,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bbl/s" ] + "Abbreviations": ["bbl/s"] } ] }, @@ -394,11 +395,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "mm³/s" ] + "Abbreviations": ["mm³/s"] }, { "Culture": "ru-RU", - "Abbreviations": [ "мм³/с" ] + "Abbreviations": ["мм³/с"] } ] }, @@ -410,7 +411,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "af/s" ] + "Abbreviations": ["af/s"] } ] }, @@ -422,7 +423,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "af/m" ] + "Abbreviations": ["af/m"] } ] }, @@ -434,7 +435,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "af/h" ] + "Abbreviations": ["af/h"] } ] }, @@ -446,9 +447,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "af/d" ] + "Abbreviations": ["af/d"] } ] } ] -} +} \ No newline at end of file diff --git a/Common/UnitDefinitions/VolumePerLength.json b/Common/UnitDefinitions/VolumePerLength.json index 2098ba6030..73bd8e4f85 100644 --- a/Common/UnitDefinitions/VolumePerLength.json +++ b/Common/UnitDefinitions/VolumePerLength.json @@ -18,7 +18,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "m³/m" ] + "Abbreviations": ["m³/m"] } ] }, @@ -34,7 +34,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "l/m" ] + "Abbreviations": ["l/m"] } ] }, @@ -47,9 +47,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [ "bbl/ft" ] + "Abbreviations": ["bbl/ft"] } ] } ] -} +} \ No newline at end of file diff --git a/UnitsNet.Benchmark/Program.cs b/UnitsNet.Benchmark/Program.cs index d51d42b653..a7a45e6c7f 100644 --- a/UnitsNet.Benchmark/Program.cs +++ b/UnitsNet.Benchmark/Program.cs @@ -1,4 +1,7 @@ -using BenchmarkDotNet.Attributes; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; using UnitsNet.Units; @@ -8,7 +11,7 @@ namespace UnitsNet.Benchmark public class UnitsNetBenchmarks { private Length length = Length.FromMeters(3.0); - private IQuantity lengthIQuantity = Length.FromMeters(3.0); + private readonly IQuantity lengthIQuantity = Length.FromMeters(3.0); [Benchmark] public Length Constructor() => new Length(3.0, LengthUnit.Meter); @@ -62,9 +65,9 @@ public class UnitsNetBenchmarks public string IQuantity_ToStringTest() => lengthIQuantity.ToString(); } - class Program + internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var summary = BenchmarkRunner.Run(); } diff --git a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs index 0a62526b9c..e7c7ac0a9c 100644 --- a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs +++ b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs @@ -29,35 +29,67 @@ private T DeserializeObject(string json) public class Serialize : UnitsNetJsonConverterTests { + [Fact(Skip = "Not supported in older versions of serialization")] + public void ArrayValue_ExpectJsonArray() + { + Frequency[] testObj = {Frequency.FromHertz(10), Frequency.FromHertz(10)}; + + var expectedJson = "[\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "]"; + + var json = SerializeObject(testObj); + + Assert.Equal(expectedJson, json); + } + + [Fact(Skip = "Not supported in older versions of serialization")] + public void EmptyArrayValue_ExpectJsonArray() + { + var testObj = new Frequency[0]; + + var expectedJson = "[]"; + + var json = SerializeObject(testObj); + Assert.Equal(expectedJson, json); + } + [Fact] public void Information_CanSerializeVeryLargeValues() { - Information i = Information.FromExabytes(1E+9); + var i = Information.FromExabytes(1E+9); var expectedJson = "{\n \"Unit\": \"InformationUnit.Exabyte\",\n \"Value\": 1000000000.0\n}"; - string json = SerializeObject(i); + var json = SerializeObject(i); Assert.Equal(expectedJson, json); } [Fact] - public void Mass_ExpectConstructedValueAndUnit() + public void Information_ExpectConstructedValueAndUnit() { - Mass mass = Mass.FromPounds(200); - var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; + var quantity = Information.FromKilobytes(54); + var expectedJson = "{\n \"Unit\": \"InformationUnit.Kilobyte\",\n \"Value\": 54.0\n}"; - string json = SerializeObject(mass); + var json = SerializeObject(quantity); Assert.Equal(expectedJson, json); } [Fact] - public void Information_ExpectConstructedValueAndUnit() + public void Mass_ExpectConstructedValueAndUnit() { - Information quantity = Information.FromKilobytes(54); - var expectedJson = "{\n \"Unit\": \"InformationUnit.Kilobyte\",\n \"Value\": 54.0\n}"; + var mass = Mass.FromPounds(200); + var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; - string json = SerializeObject(quantity); + var json = SerializeObject(mass); Assert.Equal(expectedJson, json); } @@ -68,7 +100,7 @@ public void NonNullNullableValue_ExpectJsonUnaffected() Mass? nullableMass = Mass.FromKilograms(10); var expectedJson = "{\n \"Unit\": \"MassUnit.Kilogram\",\n \"Value\": 10.0\n}"; - string json = SerializeObject(nullableMass); + var json = SerializeObject(nullableMass); // There shouldn't be any change in the JSON for the non-null nullable value. Assert.Equal(expectedJson, json); @@ -77,25 +109,21 @@ public void NonNullNullableValue_ExpectJsonUnaffected() [Fact] public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() { - var testObj = new TestObj - { - NullableFrequency = Frequency.FromHertz(10), - NonNullableFrequency = Frequency.FromHertz(10) - }; + var testObj = new TestObj {NullableFrequency = Frequency.FromHertz(10), NonNullableFrequency = Frequency.FromHertz(10)}; // Ugly manually formatted JSON string is used because string literals with newlines are rendered differently // on the build server (i.e. the build server uses '\r' instead of '\n') - string expectedJson = "{\n" + - " \"NullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " \"NonNullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "}"; - - string json = SerializeObject(testObj); + var expectedJson = "{\n" + + " \"NullableFrequency\": {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " \"NonNullableFrequency\": {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "}"; + + var json = SerializeObject(testObj); Assert.Equal(expectedJson, json); } @@ -103,61 +131,94 @@ public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() [Fact] public void NullValue_ExpectJsonContainsNullString() { - string json = SerializeObject(null); + var json = SerializeObject(null); Assert.Equal("null", json); } [Fact] public void Ratio_ExpectDecimalFractionsUsedAsBaseValueAndUnit() { - Ratio ratio = Ratio.FromPartsPerThousand(250); + var ratio = Ratio.FromPartsPerThousand(250); var expectedJson = "{\n \"Unit\": \"RatioUnit.PartPerThousand\",\n \"Value\": 250.0\n}"; - string json = SerializeObject(ratio); + var json = SerializeObject(ratio); Assert.Equal(expectedJson, json); } + } + + public class Deserialize : UnitsNetJsonConverterTests + { + private static JsonSerializerSettings CreateJsonSerializerSettings() + { + var jsonSerializerSettings = new JsonSerializerSettings {Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.Auto}; + jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); + return jsonSerializerSettings; + } [Fact(Skip = "Not supported in older versions of serialization")] - public void ArrayValue_ExpectJsonArray() + public void ArrayOfUnits_ExpectCorrectlyDeserialized() { - Frequency[] testObj = new Frequency[] { Frequency.FromHertz(10), Frequency.FromHertz(10) }; + Frequency[] expected = {Frequency.FromHertz(10), Frequency.FromHertz(10)}; - string expectedJson = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; + var json = "[\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "]"; - string json = SerializeObject(testObj); + var result = DeserializeObject(json); - Assert.Equal(expectedJson, json); + Assert.Equal(expected, result); + } + + [Fact] + public void ClassInIComparable_ExpectUnitCorrectlyDeserialized() + { + var testObjWithIComparable = new TestObjWithIComparable {Value = new ComparableClass {Value = 10}}; + var jsonSerializerSettings = CreateJsonSerializerSettings(); + + var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + + Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value.GetType()); + Assert.Equal(10d, ((ComparableClass) deserializedTestObject.Value).Value); + } + + [Fact] + public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized() + { + var testObjWithIComparable = new TestObjWithIComparable {Value = 10.0}; + var jsonSerializerSettings = CreateJsonSerializerSettings(); + + var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + + Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); + Assert.Equal(10d, (double) deserializedTestObject.Value); } [Fact(Skip = "Not supported in older versions of serialization")] - public void EmptyArrayValue_ExpectJsonArray() + public void EmptyArray_ExpectCorrectlyDeserialized() { - Frequency[] testObj = new Frequency[0]; + var json = "[]"; - string expectedJson = "[]"; + var result = DeserializeObject(json); - string json = SerializeObject(testObj); - Assert.Equal(expectedJson, json); + Assert.Empty(result); } - } - public class Deserialize : UnitsNetJsonConverterTests - { [Fact] public void Information_CanDeserializeVeryLargeValues() { - Information original = Information.FromExabytes(1E+9); - string json = SerializeObject(original); + var original = Information.FromExabytes(1E+9); + var json = SerializeObject(original); var deserialized = DeserializeObject(json); Assert.Equal(original, deserialized); @@ -166,8 +227,8 @@ public void Information_CanDeserializeVeryLargeValues() [Fact] public void Mass_ExpectJsonCorrectlyDeserialized() { - Mass originalMass = Mass.FromKilograms(33.33); - string json = SerializeObject(originalMass); + var originalMass = Mass.FromKilograms(33.33); + var json = SerializeObject(originalMass); var deserializedMass = DeserializeObject(json); @@ -178,9 +239,9 @@ public void Mass_ExpectJsonCorrectlyDeserialized() public void NonNullNullableValue_ExpectValueDeserializedCorrectly() { Mass? nullableMass = Mass.FromKilograms(10); - string json = SerializeObject(nullableMass); + var json = SerializeObject(nullableMass); - Mass? deserializedNullableMass = DeserializeObject(json); + var deserializedNullableMass = DeserializeObject(json); Assert.Equal(nullableMass.Value, deserializedNullableMass); } @@ -188,12 +249,8 @@ public void NonNullNullableValue_ExpectValueDeserializedCorrectly() [Fact] public void NonNullNullableValueNestedInObject_ExpectValueDeserializedCorrectly() { - var testObj = new TestObj - { - NullableFrequency = Frequency.FromHertz(10), - NonNullableFrequency = Frequency.FromHertz(10) - }; - string json = SerializeObject(testObj); + var testObj = new TestObj {NullableFrequency = Frequency.FromHertz(10), NonNullableFrequency = Frequency.FromHertz(10)}; + var json = SerializeObject(testObj); var deserializedTestObj = DeserializeObject(json); @@ -203,7 +260,7 @@ public void NonNullNullableValueNestedInObject_ExpectValueDeserializedCorrectly( [Fact] public void NullValue_ExpectNullReturned() { - string json = SerializeObject(null); + var json = SerializeObject(null); var deserializedNullMass = DeserializeObject(json); Assert.Null(deserializedNullMass); @@ -212,96 +269,22 @@ public void NullValue_ExpectNullReturned() [Fact] public void NullValueNestedInObject_ExpectValueDeserializedToNullCorrectly() { - var testObj = new TestObj - { - NullableFrequency = null, - NonNullableFrequency = Frequency.FromHertz(10) - }; - string json = SerializeObject(testObj); + var testObj = new TestObj {NullableFrequency = null, NonNullableFrequency = Frequency.FromHertz(10)}; + var json = SerializeObject(testObj); var deserializedTestObj = DeserializeObject(json); Assert.Null(deserializedTestObj.NullableFrequency); } - [Fact] - public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized() - { - Mass originalMass = Mass.FromKilograms(33.33); - string json = SerializeObject(originalMass); - // Someone manually changed the serialized JSON string to 1000 grams. - json = json.Replace("33.33", "1000"); - json = json.Replace("MassUnit.Kilogram", "MassUnit.Gram"); - - var deserializedMass = DeserializeObject(json); - - // The original value serialized was 33.33 kg, but someone edited the JSON to be 1000 g. We expect the JSON is - // still deserializable, and the correct value of 1000 g is obtained. - Assert.Equal(1000, deserializedMass.Grams); - } - - [Fact] - public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = Power.FromWatts(10) - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - - var deserializedTestObject = JsonConvert.DeserializeObject(json,jsonSerializerSettings); - - Assert.Equal(typeof(Power), deserializedTestObject.Value.GetType()); - Assert.Equal(Power.FromWatts(10), (Power)deserializedTestObject.Value); - } - - [Fact] - public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = 10.0 - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, (double)deserializedTestObject.Value); - } - - [Fact] - public void ClassInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = new ComparableClass() { Value = 10 } - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, ((ComparableClass) deserializedTestObject.Value).Value); - } - [Fact] public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues() { - TestObjWithValueAndUnit testObjWithValueAndUnit = new TestObjWithValueAndUnit() - { - Value = 5, - Unit = "Test", - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); + var testObjWithValueAndUnit = new TestObjWithValueAndUnit {Value = 5, Unit = "Test"}; + var jsonSerializerSettings = CreateJsonSerializerSettings(); - string json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings); - TestObjWithValueAndUnit deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + var json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings); + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); Assert.Equal(5d, deserializedTestObject.Value); @@ -311,15 +294,13 @@ public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues() [Fact] public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeserialized() { - TestObjWithThreeIComparable testObjWithIComparable = new TestObjWithThreeIComparable() + var testObjWithIComparable = new TestObjWithThreeIComparable { - Value1 = 10.0, - Value2 = Power.FromWatts(19), - Value3 = new ComparableClass() { Value = 10 }, + Value1 = 10.0, Value2 = Power.FromWatts(19), Value3 = new ComparableClass {Value = 10} }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); + var jsonSerializerSettings = CreateJsonSerializerSettings(); - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); Assert.Equal(typeof(double), deserializedTestObject.Value1.GetType()); @@ -330,46 +311,34 @@ public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeser Assert.Equal(testObjWithIComparable.Value3, deserializedTestObject.Value3); } - [Fact(Skip = "Not supported in older versions of serialization")] - public void ArrayOfUnits_ExpectCorrectlyDeserialized() + [Fact] + public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized() { - Frequency[] expected = new Frequency[] { Frequency.FromHertz(10), Frequency.FromHertz(10) }; - - string json = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; + var originalMass = Mass.FromKilograms(33.33); + var json = SerializeObject(originalMass); + // Someone manually changed the serialized JSON string to 1000 grams. + json = json.Replace("33.33", "1000"); + json = json.Replace("MassUnit.Kilogram", "MassUnit.Gram"); - Frequency[] result = DeserializeObject(json); + var deserializedMass = DeserializeObject(json); - Assert.Equal(expected, result); + // The original value serialized was 33.33 kg, but someone edited the JSON to be 1000 g. We expect the JSON is + // still deserializable, and the correct value of 1000 g is obtained. + Assert.Equal(1000, deserializedMass.Grams); } - [Fact(Skip = "Not supported in older versions of serialization")] - public void EmptyArray_ExpectCorrectlyDeserialized() + [Fact] + public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() { - string json = "[]"; + var testObjWithIComparable = new TestObjWithIComparable {Value = Power.FromWatts(10)}; + var jsonSerializerSettings = CreateJsonSerializerSettings(); - Frequency[] result = DeserializeObject(json); + var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - Assert.Empty(result); - } + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - private static JsonSerializerSettings CreateJsonSerializerSettings() - { - var jsonSerializerSettings = new JsonSerializerSettings() - { - Formatting = Formatting.Indented, - TypeNameHandling = TypeNameHandling.Auto - }; - jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); - return jsonSerializerSettings; + Assert.Equal(typeof(Power), deserializedTestObject.Value.GetType()); + Assert.Equal(Power.FromWatts(10), (Power) deserializedTestObject.Value); } } @@ -386,16 +355,17 @@ private class TestObjWithValueAndUnit : IComparable public int CompareTo(object obj) { - return ((IComparable)Value).CompareTo(obj); + return ((IComparable) Value).CompareTo(obj); } } private class ComparableClass : IComparable { public int Value { get; set; } + public int CompareTo(object obj) { - return ((IComparable)Value).CompareTo(obj); + return ((IComparable) Value).CompareTo(obj); } // Needed for virfying that the deserialized object is the same, should not affect the serilization code @@ -405,7 +375,8 @@ public override bool Equals(object obj) { return false; } - return Value.Equals(((ComparableClass)obj).Value); + + return Value.Equals(((ComparableClass) obj).Value); } public override int GetHashCode() diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs index 8cb662fe22..86483ae085 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs @@ -30,23 +30,44 @@ private T DeserializeObject(string json) public class Serialize : UnitsNetJsonConverterTests { [Fact] - public void Information_CanSerializeVeryLargeValues() + public void ArrayValue_ExpectJsonArray() { - Information i = Information.FromExabytes(1E+9); - var expectedJson = "{\n \"Unit\": \"InformationUnit.Exabyte\",\n \"Value\": 1000000000.0\n}"; + Frequency[] testObj = {Frequency.FromHertz(10), Frequency.FromHertz(10)}; - string json = SerializeObject(i); + var expectedJson = "[\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "]"; + + var json = SerializeObject(testObj); Assert.Equal(expectedJson, json); } [Fact] - public void Mass_ExpectConstructedValueAndUnit() + public void EmptyArrayValue_ExpectJsonArray() { - Mass mass = Mass.FromPounds(200); - var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; + var testObj = new Frequency[0]; - string json = SerializeObject(mass); + var expectedJson = "[]"; + + var json = SerializeObject(testObj); + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Information_CanSerializeVeryLargeValues() + { + var i = Information.FromExabytes(1E+9); + var expectedJson = "{\n \"Unit\": \"InformationUnit.Exabyte\",\n \"Value\": 1000000000.0\n}"; + + var json = SerializeObject(i); Assert.Equal(expectedJson, json); } @@ -54,10 +75,21 @@ public void Mass_ExpectConstructedValueAndUnit() [Fact] public void Information_ExpectConstructedValueAndUnit() { - Information quantity = Information.FromKilobytes(54); + var quantity = Information.FromKilobytes(54); var expectedJson = "{\n \"Unit\": \"InformationUnit.Kilobyte\",\n \"Value\": 54.0\n}"; - string json = SerializeObject(quantity); + var json = SerializeObject(quantity); + + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Mass_ExpectConstructedValueAndUnit() + { + var mass = Mass.FromPounds(200); + var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; + + var json = SerializeObject(mass); Assert.Equal(expectedJson, json); } @@ -68,7 +100,7 @@ public void NonNullNullableValue_ExpectJsonUnaffected() Mass? nullableMass = Mass.FromKilograms(10); var expectedJson = "{\n \"Unit\": \"MassUnit.Kilogram\",\n \"Value\": 10.0\n}"; - string json = SerializeObject(nullableMass); + var json = SerializeObject(nullableMass); // There shouldn't be any change in the JSON for the non-null nullable value. Assert.Equal(expectedJson, json); @@ -77,25 +109,21 @@ public void NonNullNullableValue_ExpectJsonUnaffected() [Fact] public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() { - var testObj = new TestObj - { - NullableFrequency = Frequency.FromHertz(10), - NonNullableFrequency = Frequency.FromHertz(10) - }; + var testObj = new TestObj {NullableFrequency = Frequency.FromHertz(10), NonNullableFrequency = Frequency.FromHertz(10)}; // Ugly manually formatted JSON string is used because string literals with newlines are rendered differently // on the build server (i.e. the build server uses '\r' instead of '\n') - string expectedJson = "{\n" + - " \"NullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " \"NonNullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "}"; - - string json = SerializeObject(testObj); + var expectedJson = "{\n" + + " \"NullableFrequency\": {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " \"NonNullableFrequency\": {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "}"; + + var json = SerializeObject(testObj); Assert.Equal(expectedJson, json); } @@ -103,61 +131,94 @@ public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() [Fact] public void NullValue_ExpectJsonContainsNullString() { - string json = SerializeObject(null); + var json = SerializeObject(null); Assert.Equal("null", json); } [Fact] public void Ratio_ExpectDecimalFractionsUsedAsBaseValueAndUnit() { - Ratio ratio = Ratio.FromPartsPerThousand(250); + var ratio = Ratio.FromPartsPerThousand(250); var expectedJson = "{\n \"Unit\": \"RatioUnit.PartPerThousand\",\n \"Value\": 250.0\n}"; - string json = SerializeObject(ratio); + var json = SerializeObject(ratio); Assert.Equal(expectedJson, json); } + } + + public class Deserialize : UnitsNetJsonConverterTests + { + private static JsonSerializerSettings CreateJsonSerializerSettings() + { + var jsonSerializerSettings = new JsonSerializerSettings {Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.Auto}; + jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); + return jsonSerializerSettings; + } [Fact] - public void ArrayValue_ExpectJsonArray() + public void ArrayOfUnits_ExpectCorrectlyDeserialized() { - Frequency[] testObj = { Frequency.FromHertz(10), Frequency.FromHertz(10) }; + Frequency[] expected = {Frequency.FromHertz(10), Frequency.FromHertz(10)}; - string expectedJson = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; + var json = "[\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "]"; - string json = SerializeObject(testObj); + var result = DeserializeObject(json); - Assert.Equal(expectedJson, json); + Assert.Equal(expected, result); } [Fact] - public void EmptyArrayValue_ExpectJsonArray() + public void ClassInIComparable_ExpectUnitCorrectlyDeserialized() { - Frequency[] testObj = new Frequency[0]; + var testObjWithIComparable = new TestObjWithIComparable {Value = new ComparableClass {Value = 10}}; + var jsonSerializerSettings = CreateJsonSerializerSettings(); - string expectedJson = "[]"; + var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - string json = SerializeObject(testObj); - Assert.Equal(expectedJson, json); + Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value.GetType()); + Assert.Equal(10d, ((ComparableClass) deserializedTestObject.Value).Value); + } + + [Fact] + public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized() + { + var testObjWithIComparable = new TestObjWithIComparable {Value = 10.0}; + var jsonSerializerSettings = CreateJsonSerializerSettings(); + + var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + + Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); + Assert.Equal(10d, (double) deserializedTestObject.Value); + } + + [Fact] + public void EmptyArray_ExpectCorreclyDeserialized() + { + var json = "[]"; + + var result = DeserializeObject(json); + + Assert.Empty(result); } - } - public class Deserialize : UnitsNetJsonConverterTests - { [Fact] public void Information_CanDeserializeVeryLargeValues() { - Information original = Information.FromExabytes(1E+9); - string json = SerializeObject(original); + var original = Information.FromExabytes(1E+9); + var json = SerializeObject(original); var deserialized = DeserializeObject(json); Assert.Equal(original, deserialized); @@ -166,8 +227,8 @@ public void Information_CanDeserializeVeryLargeValues() [Fact] public void Mass_ExpectJsonCorrectlyDeserialized() { - Mass originalMass = Mass.FromKilograms(33.33); - string json = SerializeObject(originalMass); + var originalMass = Mass.FromKilograms(33.33); + var json = SerializeObject(originalMass); var deserializedMass = DeserializeObject(json); @@ -178,9 +239,9 @@ public void Mass_ExpectJsonCorrectlyDeserialized() public void NonNullNullableValue_ExpectValueDeserializedCorrectly() { Mass? nullableMass = Mass.FromKilograms(10); - string json = SerializeObject(nullableMass); + var json = SerializeObject(nullableMass); - Mass? deserializedNullableMass = DeserializeObject(json); + var deserializedNullableMass = DeserializeObject(json); Assert.Equal(nullableMass.Value, deserializedNullableMass); } @@ -188,12 +249,8 @@ public void NonNullNullableValue_ExpectValueDeserializedCorrectly() [Fact] public void NonNullNullableValueNestedInObject_ExpectValueDeserializedCorrectly() { - var testObj = new TestObj - { - NullableFrequency = Frequency.FromHertz(10), - NonNullableFrequency = Frequency.FromHertz(10) - }; - string json = SerializeObject(testObj); + var testObj = new TestObj {NullableFrequency = Frequency.FromHertz(10), NonNullableFrequency = Frequency.FromHertz(10)}; + var json = SerializeObject(testObj); var deserializedTestObj = DeserializeObject(json); @@ -203,7 +260,7 @@ public void NonNullNullableValueNestedInObject_ExpectValueDeserializedCorrectly( [Fact] public void NullValue_ExpectNullReturned() { - string json = SerializeObject(null); + var json = SerializeObject(null); var deserializedNullMass = DeserializeObject(json); Assert.Null(deserializedNullMass); @@ -212,96 +269,22 @@ public void NullValue_ExpectNullReturned() [Fact] public void NullValueNestedInObject_ExpectValueDeserializedToNullCorrectly() { - var testObj = new TestObj - { - NullableFrequency = null, - NonNullableFrequency = Frequency.FromHertz(10) - }; - string json = SerializeObject(testObj); + var testObj = new TestObj {NullableFrequency = null, NonNullableFrequency = Frequency.FromHertz(10)}; + var json = SerializeObject(testObj); var deserializedTestObj = DeserializeObject(json); Assert.Null(deserializedTestObj.NullableFrequency); } - [Fact] - public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized() - { - Mass originalMass = Mass.FromKilograms(33.33); - string json = SerializeObject(originalMass); - // Someone manually changed the serialized JSON string to 1000 grams. - json = json.Replace("33.33", "1000"); - json = json.Replace("MassUnit.Kilogram", "MassUnit.Gram"); - - var deserializedMass = DeserializeObject(json); - - // The original value serialized was 33.33 kg, but someone edited the JSON to be 1000 g. We expect the JSON is - // still deserializable, and the correct value of 1000 g is obtained. - Assert.Equal(1000, deserializedMass.Grams); - } - - [Fact] - public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = Power.FromWatts(10) - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - - var deserializedTestObject = JsonConvert.DeserializeObject(json,jsonSerializerSettings); - - Assert.Equal(typeof(Power), deserializedTestObject.Value.GetType()); - Assert.Equal(Power.FromWatts(10), (Power)deserializedTestObject.Value); - } - - [Fact] - public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = 10.0 - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, (double)deserializedTestObject.Value); - } - - [Fact] - public void ClassInIComparable_ExpectUnitCorrectlyDeserialized() - { - TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() - { - Value = new ComparableClass() { Value = 10 } - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, ((ComparableClass) deserializedTestObject.Value).Value); - } - [Fact] public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues() { - TestObjWithValueAndUnit testObjWithValueAndUnit = new TestObjWithValueAndUnit() - { - Value = 5, - Unit = "Test", - }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); + var testObjWithValueAndUnit = new TestObjWithValueAndUnit {Value = 5, Unit = "Test"}; + var jsonSerializerSettings = CreateJsonSerializerSettings(); - string json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings); - TestObjWithValueAndUnit deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + var json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings); + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); Assert.Equal(5d, deserializedTestObject.Value); @@ -311,15 +294,13 @@ public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues() [Fact] public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeserialized() { - TestObjWithThreeIComparable testObjWithIComparable = new TestObjWithThreeIComparable() + var testObjWithIComparable = new TestObjWithThreeIComparable { - Value1 = 10.0, - Value2 = Power.FromWatts(19), - Value3 = new ComparableClass() { Value = 10 }, + Value1 = 10.0, Value2 = Power.FromWatts(19), Value3 = new ComparableClass {Value = 10} }; - JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); + var jsonSerializerSettings = CreateJsonSerializerSettings(); - string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); Assert.Equal(typeof(double), deserializedTestObject.Value1.GetType()); @@ -331,45 +312,33 @@ public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeser } [Fact] - public void ArrayOfUnits_ExpectCorrectlyDeserialized() + public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized() { - Frequency[] expected = { Frequency.FromHertz(10), Frequency.FromHertz(10) }; - - string json = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; + var originalMass = Mass.FromKilograms(33.33); + var json = SerializeObject(originalMass); + // Someone manually changed the serialized JSON string to 1000 grams. + json = json.Replace("33.33", "1000"); + json = json.Replace("MassUnit.Kilogram", "MassUnit.Gram"); - Frequency[] result = DeserializeObject(json); + var deserializedMass = DeserializeObject(json); - Assert.Equal(expected, result); + // The original value serialized was 33.33 kg, but someone edited the JSON to be 1000 g. We expect the JSON is + // still deserializable, and the correct value of 1000 g is obtained. + Assert.Equal(1000, deserializedMass.Grams); } [Fact] - public void EmptyArray_ExpectCorreclyDeserialized() + public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() { - string json = "[]"; + var testObjWithIComparable = new TestObjWithIComparable {Value = Power.FromWatts(10)}; + var jsonSerializerSettings = CreateJsonSerializerSettings(); - Frequency[] result = DeserializeObject(json); + var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - Assert.Empty(result); - } + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - private static JsonSerializerSettings CreateJsonSerializerSettings() - { - var jsonSerializerSettings = new JsonSerializerSettings() - { - Formatting = Formatting.Indented, - TypeNameHandling = TypeNameHandling.Auto - }; - jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); - return jsonSerializerSettings; + Assert.Equal(typeof(Power), deserializedTestObject.Value.GetType()); + Assert.Equal(Power.FromWatts(10), (Power) deserializedTestObject.Value); } } @@ -386,16 +355,17 @@ private class TestObjWithValueAndUnit : IComparable public int CompareTo(object obj) { - return ((IComparable)Value).CompareTo(obj); + return ((IComparable) Value).CompareTo(obj); } } private class ComparableClass : IComparable { public int Value { get; set; } + public int CompareTo(object obj) { - return ((IComparable)Value).CompareTo(obj); + return ((IComparable) Value).CompareTo(obj); } // Needed for virfying that the deserialized object is the same, should not affect the serilization code @@ -405,7 +375,8 @@ public override bool Equals(object obj) { return false; } - return Value.Equals(((ComparableClass)obj).Value); + + return Value.Equals(((ComparableClass) obj).Value); } public override int GetHashCode() diff --git a/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs b/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs index 930acb1080..866600bdb5 100644 --- a/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs +++ b/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using System.Collections.Generic; using System.Reflection; @@ -21,17 +24,23 @@ internal static PropertyInfo GetProperty(this Type type, string name) internal static IEnumerable GetDeclaredMethods(this Type someType) { - Type t = someType; + var t = someType; while (t != null) { #if (NET40 || NET35 || NET20 || SILVERLIGHT) foreach (var m in t.GetMethods()) + { yield return m; + } + t = t.BaseType; #else - TypeInfo ti = t.GetTypeInfo(); - foreach (MethodInfo m in ti.DeclaredMethods) + var ti = t.GetTypeInfo(); + foreach (var m in ti.DeclaredMethods) + { yield return m; + } + t = ti.BaseType; #endif } diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs index c8c460ccc8..215fa8039d 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs @@ -38,9 +38,11 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist JsonSerializer serializer) { if (reader.ValueType != null) + { return reader.Value; + } - object obj = TryDeserializeIComparable(reader, serializer); + var obj = TryDeserializeIComparable(reader, serializer); if (obj is Array values) { // Create array with the requested type, such as `Length[]` or `Frequency[]` @@ -50,33 +52,32 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist var i = 0; foreach (ValueUnit valueUnit in values) { - IQuantity quantity = ParseValueUnit(valueUnit); + var quantity = ParseValueUnit(valueUnit); arrayOfQuantities.SetValue(quantity, i++); } return arrayOfQuantities; } + else if (obj is ValueUnit valueUnit) { return ParseValueUnit(valueUnit); } - else - { - return obj; - } + + return obj; } private static IQuantity ParseValueUnit(ValueUnit vu) { // "MassUnit.Kilogram" => "MassUnit" and "Kilogram" - string unitEnumTypeName = vu.Unit.Split('.')[0]; - string unitEnumValue = vu.Unit.Split('.')[1]; + var unitEnumTypeName = vu.Unit.Split('.')[0]; + var unitEnumValue = vu.Unit.Split('.')[1]; // "UnitsNet.Units.MassUnit,UnitsNet" - string unitEnumTypeAssemblyQualifiedName = "UnitsNet.Units." + unitEnumTypeName + ",UnitsNet"; + var unitEnumTypeAssemblyQualifiedName = "UnitsNet.Units." + unitEnumTypeName + ",UnitsNet"; // -- see http://stackoverflow.com/a/6465096/1256096 for details - Type unitEnumType = Type.GetType(unitEnumTypeAssemblyQualifiedName); + var unitEnumType = Type.GetType(unitEnumTypeAssemblyQualifiedName); if (unitEnumType == null) { var ex = new UnitsNetException("Unable to find enum type."); @@ -84,45 +85,34 @@ private static IQuantity ParseValueUnit(ValueUnit vu) throw ex; } - double value = vu.Value; - Enum unitValue = (Enum)Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram + var value = vu.Value; + var unitValue = (Enum) Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram return Quantity.From(value, unitValue); } private static object TryDeserializeIComparable(JsonReader reader, JsonSerializer serializer) { - JToken token = JToken.Load(reader); + var token = JToken.Load(reader); if (token is JArray) { - object[] results = token.Children().Select(item => TryDeserializeIComparable(item, serializer)).ToArray(); + var results = token.Children().Select(item => TryDeserializeIComparable(item, serializer)).ToArray(); return results; } - else - { - return TryDeserializeIComparable(token, serializer); - } + + return TryDeserializeIComparable(token, serializer); } private static object TryDeserializeIComparable(JToken token, JsonSerializer serializer) { if (!token.HasValues || token[nameof(ValueUnit.Unit)] == null || token[nameof(ValueUnit.Value)] == null) { - var localSerializer = new JsonSerializer - { - TypeNameHandling = serializer.TypeNameHandling, - }; + var localSerializer = new JsonSerializer {TypeNameHandling = serializer.TypeNameHandling}; return token.ToObject(localSerializer); } - else - { - return new ValueUnit - { - Unit = token[nameof(ValueUnit.Unit)].ToString(), - Value = token[nameof(ValueUnit.Value)].ToObject() - }; - } + + return new ValueUnit {Unit = token[nameof(ValueUnit.Unit)].ToString(), Value = token[nameof(ValueUnit.Value)].ToObject()}; } /// @@ -137,10 +127,7 @@ public override void WriteJson(JsonWriter writer, object obj, JsonSerializer ser // ValueUnit should be written as usual (but read in a custom way) if (obj is ValueUnit valueUnit) { - var localSerializer = new JsonSerializer - { - TypeNameHandling = serializer.TypeNameHandling, - }; + var localSerializer = new JsonSerializer {TypeNameHandling = serializer.TypeNameHandling}; var t = JToken.FromObject(valueUnit, localSerializer); t.WriteTo(writer); @@ -165,8 +152,7 @@ private static ValueUnit ToValueUnit(IQuantity value) return new ValueUnit { // See ValueUnit about precision loss for quantities using decimal type. - Value = value.Value, - Unit = $"{value.QuantityInfo.UnitType.Name}.{value.Unit}" + Value = value.Value, Unit = $"{value.QuantityInfo.UnitType.Name}.{value.Unit}" }; } @@ -178,7 +164,6 @@ private static ValueUnit ToValueUnit(IQuantity value) /// in a loss of precision when serializing/deserializing to decimal. /// Decimal is the highest precision type available in .NET, but has a smaller /// range than double. - /// /// Json: Support decimal precision #503 /// https://github.com/angularsen/UnitsNet/issues/503 /// @@ -198,13 +183,15 @@ private class ValueUnit public override bool CanConvert(Type objectType) { if (IsNullable(objectType)) + { return CanConvertNullable(objectType); + } return objectType.Namespace != null && - (objectType.Namespace.Equals(nameof(UnitsNet)) || - objectType == typeof(ValueUnit) || - // All unit types implement IComparable - objectType == typeof(IComparable)); + (objectType.Namespace.Equals(nameof(UnitsNet)) || + objectType == typeof(ValueUnit) || + // All unit types implement IComparable + objectType == typeof(IComparable)); } /// diff --git a/UnitsNet.Tests/AssemblyAttributeTests.cs b/UnitsNet.Tests/AssemblyAttributeTests.cs index 754846727d..b48302b531 100644 --- a/UnitsNet.Tests/AssemblyAttributeTests.cs +++ b/UnitsNet.Tests/AssemblyAttributeTests.cs @@ -11,25 +11,25 @@ namespace UnitsNet.Tests public class AssemblyAttributeTests { [Fact] - public static void AssemblyShouldBeClsCompliant() + public static void AssemblyCopyrightShouldContain2013() { var assembly = typeof(Length).GetTypeInfo().Assembly; - var attributes = assembly.CustomAttributes.Select(x => x.AttributeType); - Assert.Contains(typeof(CLSCompliantAttribute), attributes); + var copyrightAttribute = assembly + .CustomAttributes + .Single(x => x.AttributeType == typeof(AssemblyCopyrightAttribute)); + var copyrightString = copyrightAttribute.ConstructorArguments.Single().Value.ToString(); + var expectedYear = "2013"; + Assert.Contains(expectedYear, copyrightString); } [Fact] - public static void AssemblyCopyrightShouldContain2013() + public static void AssemblyShouldBeClsCompliant() { var assembly = typeof(Length).GetTypeInfo().Assembly; - var copyrightAttribute = assembly - .CustomAttributes - .Single(x => x.AttributeType == typeof(AssemblyCopyrightAttribute)); - string copyrightString = copyrightAttribute.ConstructorArguments.Single().Value.ToString(); - string expectedYear = "2013"; - Assert.Contains(expectedYear, copyrightString); + var attributes = assembly.CustomAttributes.Select(x => x.AttributeType); + Assert.Contains(typeof(CLSCompliantAttribute), attributes); } } } diff --git a/UnitsNet.Tests/AssertEx.cs b/UnitsNet.Tests/AssertEx.cs index cf90732786..aa82a72cc7 100644 --- a/UnitsNet.Tests/AssertEx.cs +++ b/UnitsNet.Tests/AssertEx.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using Xunit; namespace UnitsNet.Tests @@ -10,19 +13,21 @@ public static class AssertEx { public static void EqualTolerance(double expected, double actual, double tolerance, ComparisonType comparisonType = ComparisonType.Relative) { - if(comparisonType == ComparisonType.Relative) + if (comparisonType == ComparisonType.Relative) { - bool areEqual = Comparison.EqualsRelative(expected, actual, tolerance); + var areEqual = Comparison.EqualsRelative(expected, actual, tolerance); - double difference = Math.Abs(expected - actual); - double relativeDifference = difference / expected; + var difference = Math.Abs(expected - actual); + var relativeDifference = difference / expected; - Assert.True( areEqual, $"Values are not equal within relative tolerance: {tolerance:P4}\nExpected: {expected}\nActual: {actual}\nDiff: {relativeDifference:P4}" ); + Assert.True(areEqual, + $"Values are not equal within relative tolerance: {tolerance:P4}\nExpected: {expected}\nActual: {actual}\nDiff: {relativeDifference:P4}"); } - else if( comparisonType == ComparisonType.Absolute ) + else if (comparisonType == ComparisonType.Absolute) { - bool areEqual = Comparison.EqualsAbsolute(expected, actual, tolerance); - Assert.True( areEqual, $"Values are not equal within absolute tolerance: {tolerance}\nExpected: {expected}\nActual: {actual}\nDiff: {actual - expected:e}" ); + var areEqual = Comparison.EqualsAbsolute(expected, actual, tolerance); + Assert.True(areEqual, + $"Values are not equal within absolute tolerance: {tolerance}\nExpected: {expected}\nActual: {actual}\nDiff: {actual - expected:e}"); } } } diff --git a/UnitsNet.Tests/BaseDimensionsTests.cs b/UnitsNet.Tests/BaseDimensionsTests.cs index 9c0b593590..a1ee6266e8 100644 --- a/UnitsNet.Tests/BaseDimensionsTests.cs +++ b/UnitsNet.Tests/BaseDimensionsTests.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using System.Collections.Generic; using Xunit; @@ -6,20 +9,6 @@ namespace UnitsNet.Tests { public class BaseDimensionsTests { - [Fact] - public void ConstructorImplementedCorrectly() - { - var baseDimensions = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - - Assert.True(baseDimensions.Length == 1); - Assert.True(baseDimensions.Mass == 2); - Assert.True(baseDimensions.Time == 3); - Assert.True(baseDimensions.Current == 4); - Assert.True(baseDimensions.Temperature == 5); - Assert.True(baseDimensions.Amount == 6); - Assert.True(baseDimensions.LuminousIntensity == 7); - } - [Theory] [InlineData(1, 0, 0, 0, 0, 0, 0)] [InlineData(0, 1, 0, 0, 0, 0, 0)] @@ -55,257 +44,159 @@ public void IsDerivedQuantityImplementedProperly(int length, int mass, int time, } [Fact] - public void EqualsWorksAsExpected() - { - var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - - Assert.True(baseDimensions1.Equals(baseDimensions2)); - Assert.True(baseDimensions2.Equals(baseDimensions1)); - - Assert.False(baseDimensions1.Equals(null)); - } - - [Fact] - public void EqualityOperatorsWorkAsExpected() - { - var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - - Assert.True(baseDimensions1 == baseDimensions2); - Assert.True(baseDimensions2 == baseDimensions1); - - Assert.False(baseDimensions1 == null); - Assert.False(null == baseDimensions1); - - Assert.False(baseDimensions2 == null); - Assert.False(null == baseDimensions2); - - BaseDimensions nullBaseDimensions1 = null; - BaseDimensions nullBaseDimensions2 = null; - - Assert.True(nullBaseDimensions1 == nullBaseDimensions2); - } - - [Fact] - public void InequalityOperatorsWorkAsExpected() - { - var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var baseDimensions2 = new BaseDimensions(7, 6, 5, 4, 3, 2, 1); - - Assert.True(baseDimensions1 != baseDimensions2); - Assert.True(baseDimensions2 != baseDimensions1); - - Assert.True(baseDimensions1 != null); - Assert.True(null != baseDimensions1); - - Assert.True(baseDimensions2 != null); - Assert.True(null != baseDimensions2); - - BaseDimensions nullBaseDimensions1 = null; - BaseDimensions nullBaseDimensions2 = null; - - Assert.False(nullBaseDimensions1 != nullBaseDimensions2); - } - - [Fact] - public void MultiplyThrowsExceptionIfPassedNull() - { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - Assert.Throws(() => baseDimensions1.Multiply(null)); - } - - [Fact] - public void DivideThrowsExceptionIfPassedNull() - { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - Assert.Throws(() => baseDimensions1.Divide(null)); - } - - [Fact] - public void MultiplyOperatorThrowsExceptionWithNull() - { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - Assert.Throws(() => baseDimensions1 / null); - Assert.Throws(() => null / baseDimensions1); - } - - [Fact] - public void DivideOperatorThrowsExceptionWithNull() - { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - Assert.Throws(() => baseDimensions1 * null); - Assert.Throws(() => null * baseDimensions1); - } - - [Fact] - public void LengthDimensionsMultiplyCorrectly() + public void AmountDimensionsDivideCorrectly() { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 3, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 2, 0); - var result = baseDimensions1.Multiply(baseDimensions2); + var result = baseDimensions1.Divide(baseDimensions2); - Assert.True(result.Length == 3); + Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); + Assert.True(result.Amount == 1); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void MassDimensionsMultiplyCorrectly() + public void AmountDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 2, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 3, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 3, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 2, 0); - var result = baseDimensions1.Multiply(baseDimensions2); + var result = baseDimensions1 / baseDimensions2; Assert.True(result.Length == 0); - Assert.True(result.Mass == 5); + Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); + Assert.True(result.Amount == 1); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void TimeDimensionsMultiplyCorrectly() + public void AmountDimensionsMultiplyCorrectly() { - var baseDimensions1 = new BaseDimensions(0, 0, 3, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 4, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 6, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 7, 0); var result = baseDimensions1.Multiply(baseDimensions2); Assert.True(result.Length == 0); Assert.True(result.Mass == 0); - Assert.True(result.Time == 7); + Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); + Assert.True(result.Amount == 13); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void CurrentDimensionsMultiplyCorrectly() + public void AmountDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 6, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 7, 0); - var result = baseDimensions1.Multiply(baseDimensions2); + var result = baseDimensions1 * baseDimensions2; Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); - Assert.True(result.Current == 9); + Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); + Assert.True(result.Amount == 13); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void TemperatureDimensionsMultiplyCorrectly() + public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnInstanceProperty() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 5, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 6, 0, 0); - - var result = baseDimensions1.Multiply(baseDimensions2); + var length = Length.FromKilometers(100); + var duration = Duration.FromHours(1); - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 11); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + var calculatedDimensions = length.Dimensions.Divide(duration.Dimensions); + Assert.True(calculatedDimensions == Speed.BaseDimensions); } [Fact] - public void AmountDimensionsMultiplyCorrectly() + public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnInstancePropertyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 6, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 7, 0); + var length = Length.FromKilometers(100); + var duration = Duration.FromHours(1); - var result = baseDimensions1.Multiply(baseDimensions2); + var calculatedDimensions = length.Dimensions / duration.Dimensions; + Assert.True(calculatedDimensions == Speed.BaseDimensions); + } - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 13); - Assert.True(result.LuminousIntensity == 0); + [Fact] + public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnStaticProperty() + { + var calculatedDimensions = Length.BaseDimensions.Divide(Duration.BaseDimensions); + Assert.True(calculatedDimensions == Speed.BaseDimensions); } [Fact] - public void LuminousIntensityDimensionsMultiplyCorrectly() + public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnStaticPropertyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 7); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 8); + var calculatedDimensions = Length.BaseDimensions / Duration.BaseDimensions; + Assert.True(calculatedDimensions == Speed.BaseDimensions); + } - var result = baseDimensions1.Multiply(baseDimensions2); + [Fact] + public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnInstanceProperty() + { + var mass = Mass.FromPounds(205); + var acceleration = Acceleration.FromMetersPerSecondSquared(9.8); - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 15); + var calculatedDimensions = mass.Dimensions.Multiply(acceleration.Dimensions); + Assert.True(calculatedDimensions == Force.BaseDimensions); } [Fact] - public void LengthDimensionsDivideCorrectly() + public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnInstancePropertyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(8, 0, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(7, 0, 0, 0, 0, 0, 0); - - var result = baseDimensions1.Divide(baseDimensions2); + var mass = Mass.FromPounds(205); + var acceleration = Acceleration.FromMetersPerSecondSquared(9.8); - Assert.True(result.Length == 1); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + var calculatedDimensions = mass.Dimensions * acceleration.Dimensions; + Assert.True(calculatedDimensions == Force.BaseDimensions); } [Fact] - public void MassDimensionsDivideCorrectly() + public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnStaticProperty() { - var baseDimensions1 = new BaseDimensions(0, 7, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 6, 0, 0, 0, 0, 0); - - var result = baseDimensions1.Divide(baseDimensions2); + var calculatedDimensions = Mass.BaseDimensions.Multiply(Acceleration.BaseDimensions); + Assert.True(calculatedDimensions == Force.BaseDimensions); + } - Assert.True(result.Length == 0); - Assert.True(result.Mass == 1); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + [Fact] + public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnStaticPropertyWithOperatorOverloads() + { + var calculatedDimensions = Mass.BaseDimensions * Acceleration.BaseDimensions; + Assert.True(calculatedDimensions == Force.BaseDimensions); } [Fact] - public void TimeDimensionsDivideCorrectly() + public void CheckToStringUsingMolarEntropy() { - var baseDimensions1 = new BaseDimensions(0, 0, 6, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 5, 0, 0, 0, 0); + Assert.Equal("[Length]^2[Mass][Time]^-2[Temperature][Amount]", MolarEntropy.BaseDimensions.ToString()); + } - var result = baseDimensions1.Divide(baseDimensions2); + [Fact] + public void ConstructorImplementedCorrectly() + { + var baseDimensions = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 1); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + Assert.True(baseDimensions.Length == 1); + Assert.True(baseDimensions.Mass == 2); + Assert.True(baseDimensions.Time == 3); + Assert.True(baseDimensions.Current == 4); + Assert.True(baseDimensions.Temperature == 5); + Assert.True(baseDimensions.Amount == 6); + Assert.True(baseDimensions.LuminousIntensity == 7); } [Fact] @@ -326,88 +217,96 @@ public void CurrentDimensionsDivideCorrectly() } [Fact] - public void TemperatureDimensionsDivideCorrectly() + public void CurrentDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 4, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 3, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); - var result = baseDimensions1.Divide(baseDimensions2); + var result = baseDimensions1 / baseDimensions2; Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 1); + Assert.True(result.Current == 1); + Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void AmountDimensionsDivideCorrectly() + public void CurrentDimensionsMultiplyCorrectly() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 3, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 2, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); - var result = baseDimensions1.Divide(baseDimensions2); + var result = baseDimensions1.Multiply(baseDimensions2); Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); - Assert.True(result.Current == 0); + Assert.True(result.Current == 9); Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 1); + Assert.True(result.Amount == 0); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void LuminousIntensityDimensionsDivideCorrectly() + public void CurrentDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 2); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); - var result = baseDimensions1.Divide(baseDimensions2); + var result = baseDimensions1 * baseDimensions2; Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); - Assert.True(result.Current == 0); + Assert.True(result.Current == 9); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 1); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnStaticProperty() + public void DimensionlessPropertyIsCorrect() { - var calculatedDimensions = Length.BaseDimensions.Divide(Duration.BaseDimensions); - Assert.True(calculatedDimensions == Speed.BaseDimensions); + Assert.True(BaseDimensions.Dimensionless == new BaseDimensions(0, 0, 0, 0, 0, 0, 0)); } [Fact] - public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnInstanceProperty() + public void DivideOperatorThrowsExceptionWithNull() { - var length = Length.FromKilometers(100); - var duration = Duration.FromHours(1); - - var calculatedDimensions = length.Dimensions.Divide(duration.Dimensions); - Assert.True(calculatedDimensions == Speed.BaseDimensions); + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1 * null); + Assert.Throws(() => null * baseDimensions1); } [Fact] - public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnStaticProperty() + public void DivideThrowsExceptionIfPassedNull() { - var calculatedDimensions = Mass.BaseDimensions.Multiply(Acceleration.BaseDimensions); - Assert.True(calculatedDimensions == Force.BaseDimensions); + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1.Divide(null)); } [Fact] - public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnInstanceProperty() + public void EqualityOperatorsWorkAsExpected() { - var mass = Mass.FromPounds(205); - var acceleration = Acceleration.FromMetersPerSecondSquared(9.8); + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var calculatedDimensions = mass.Dimensions.Multiply(acceleration.Dimensions); - Assert.True(calculatedDimensions == Force.BaseDimensions); + Assert.True(baseDimensions1 == baseDimensions2); + Assert.True(baseDimensions2 == baseDimensions1); + + Assert.False(baseDimensions1 == null); + Assert.False(null == baseDimensions1); + + Assert.False(baseDimensions2 == null); + Assert.False(null == baseDimensions2); + + BaseDimensions nullBaseDimensions1 = null; + BaseDimensions nullBaseDimensions2 = null; + + Assert.True(nullBaseDimensions1 == nullBaseDimensions2); } [Fact] @@ -421,14 +320,99 @@ public void EqualityWorksAsExpectedWithOperatorOverloads() } [Fact] - public void LengthDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void EqualsWorksAsExpected() + { + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + + Assert.True(baseDimensions1.Equals(baseDimensions2)); + Assert.True(baseDimensions2.Equals(baseDimensions1)); + + Assert.False(baseDimensions1.Equals(null)); + } + + [Fact] + public void GetHashCodeWorksProperly() + { + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(7, 6, 5, 4, 3, 2, 1); + var baseDimensions3 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + + var hashSet = new HashSet(); + + hashSet.Add(baseDimensions1); + Assert.Contains(baseDimensions1, hashSet); + + hashSet.Add(baseDimensions2); + Assert.Contains(baseDimensions2, hashSet); + + // Should be the same as baseDimensions1 + Assert.Contains(baseDimensions3, hashSet); + + Assert.True(baseDimensions1.GetHashCode() != baseDimensions2.GetHashCode()); + Assert.True(baseDimensions1.GetHashCode() == baseDimensions3.GetHashCode()); + } + + [Fact] + public void InequalityOperatorsWorkAsExpected() + { + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(7, 6, 5, 4, 3, 2, 1); + + Assert.True(baseDimensions1 != baseDimensions2); + Assert.True(baseDimensions2 != baseDimensions1); + + Assert.True(baseDimensions1 != null); + Assert.True(null != baseDimensions1); + + Assert.True(baseDimensions2 != null); + Assert.True(null != baseDimensions2); + + BaseDimensions nullBaseDimensions1 = null; + BaseDimensions nullBaseDimensions2 = null; + + Assert.False(nullBaseDimensions1 != nullBaseDimensions2); + } + + [Fact] + public void IsDimensionlessMethodImplementedCorrectly() + { + Assert.True(BaseDimensions.Dimensionless.IsDimensionless()); + Assert.True(new BaseDimensions(0, 0, 0, 0, 0, 0, 0).IsDimensionless()); + + Assert.False(BaseDimensions.Dimensionless.IsBaseQuantity()); + Assert.False(BaseDimensions.Dimensionless.IsDerivedQuantity()); + + // Example case + Assert.True(Level.BaseDimensions.IsDimensionless()); + } + + [Fact] + public void LengthDimensionsDivideCorrectly() + { + var baseDimensions1 = new BaseDimensions(8, 0, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(7, 0, 0, 0, 0, 0, 0); + + var result = baseDimensions1.Divide(baseDimensions2); + + Assert.True(result.Length == 1); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); + } + + [Fact] + public void LengthDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(8, 0, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(7, 0, 0, 0, 0, 0, 0); - var result = baseDimensions1 * baseDimensions2; + var result = baseDimensions1 / baseDimensions2; - Assert.True(result.Length == 3); + Assert.True(result.Length == 1); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); @@ -438,15 +422,15 @@ public void LengthDimensionsMultiplyCorrectlyWithOperatorOverloads() } [Fact] - public void MassDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void LengthDimensionsMultiplyCorrectly() { - var baseDimensions1 = new BaseDimensions(0, 2, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 3, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - var result = baseDimensions1 * baseDimensions2; + var result = baseDimensions1.Multiply(baseDimensions2); - Assert.True(result.Length == 0); - Assert.True(result.Mass == 5); + Assert.True(result.Length == 3); + Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); @@ -455,16 +439,16 @@ public void MassDimensionsMultiplyCorrectlyWithOperatorOverloads() } [Fact] - public void TimeDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void LengthDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 3, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 4, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); var result = baseDimensions1 * baseDimensions2; - Assert.True(result.Length == 0); + Assert.True(result.Length == 3); Assert.True(result.Mass == 0); - Assert.True(result.Time == 7); + Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); @@ -472,54 +456,54 @@ public void TimeDimensionsMultiplyCorrectlyWithOperatorOverloads() } [Fact] - public void CurrentDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void LuminousIntensityDimensionsDivideCorrectly() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 2); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - var result = baseDimensions1 * baseDimensions2; + var result = baseDimensions1.Divide(baseDimensions2); Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); - Assert.True(result.Current == 9); + Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + Assert.True(result.LuminousIntensity == 1); } [Fact] - public void TemperatureDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void LuminousIntensityDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 5, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 6, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 2); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - var result = baseDimensions1 * baseDimensions2; + var result = baseDimensions1 / baseDimensions2; Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); - Assert.True(result.Temperature == 11); + Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + Assert.True(result.LuminousIntensity == 1); } [Fact] - public void AmountDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void LuminousIntensityDimensionsMultiplyCorrectly() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 6, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 7, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 7); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 8); - var result = baseDimensions1 * baseDimensions2; + var result = baseDimensions1.Multiply(baseDimensions2); Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 13); - Assert.True(result.LuminousIntensity == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 15); } [Fact] @@ -540,15 +524,15 @@ public void LuminousIntensityDimensionsMultiplyCorrectlyWithOperatorOverloads() } [Fact] - public void LengthDimensionsDivideCorrectlyWithOperatorOverloads() + public void MassDimensionsDivideCorrectly() { - var baseDimensions1 = new BaseDimensions(8, 0, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(7, 0, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 7, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 6, 0, 0, 0, 0, 0); - var result = baseDimensions1 / baseDimensions2; + var result = baseDimensions1.Divide(baseDimensions2); - Assert.True(result.Length == 1); - Assert.True(result.Mass == 0); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 1); Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); @@ -574,16 +558,16 @@ public void MassDimensionsDivideCorrectlyWithOperatorOverloads() } [Fact] - public void TimeDimensionsDivideCorrectlyWithOperatorOverloads() + public void MassDimensionsMultiplyCorrectly() { - var baseDimensions1 = new BaseDimensions(0, 0, 6, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 5, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 2, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 3, 0, 0, 0, 0, 0); - var result = baseDimensions1 / baseDimensions2; + var result = baseDimensions1.Multiply(baseDimensions2); Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 1); + Assert.True(result.Mass == 5); + Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); @@ -591,29 +575,44 @@ public void TimeDimensionsDivideCorrectlyWithOperatorOverloads() } [Fact] - public void CurrentDimensionsDivideCorrectlyWithOperatorOverloads() + public void MassDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 2, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 3, 0, 0, 0, 0, 0); - var result = baseDimensions1 / baseDimensions2; + var result = baseDimensions1 * baseDimensions2; Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); + Assert.True(result.Mass == 5); Assert.True(result.Time == 0); - Assert.True(result.Current == 1); + Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void TemperatureDimensionsDivideCorrectlyWithOperatorOverloads() + public void MultiplyOperatorThrowsExceptionWithNull() + { + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1 / null); + Assert.Throws(() => null / baseDimensions1); + } + + [Fact] + public void MultiplyThrowsExceptionIfPassedNull() + { + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1.Multiply(null)); + } + + [Fact] + public void TemperatureDimensionsDivideCorrectly() { var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 4, 0, 0); var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 3, 0, 0); - var result = baseDimensions1 / baseDimensions2; + var result = baseDimensions1.Divide(baseDimensions2); Assert.True(result.Length == 0); Assert.True(result.Mass == 0); @@ -625,10 +624,10 @@ public void TemperatureDimensionsDivideCorrectlyWithOperatorOverloads() } [Fact] - public void AmountDimensionsDivideCorrectlyWithOperatorOverloads() + public void TemperatureDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 3, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 2, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 4, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 3, 0, 0); var result = baseDimensions1 / baseDimensions2; @@ -636,107 +635,111 @@ public void AmountDimensionsDivideCorrectlyWithOperatorOverloads() Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 1); + Assert.True(result.Temperature == 1); + Assert.True(result.Amount == 0); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void LuminousIntensityDimensionsDivideCorrectlyWithOperatorOverloads() + public void TemperatureDimensionsMultiplyCorrectly() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 2); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 5, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 6, 0, 0); - var result = baseDimensions1 / baseDimensions2; + var result = baseDimensions1.Multiply(baseDimensions2); Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); + Assert.True(result.Temperature == 11); Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 1); - } - - [Fact] - public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnStaticPropertyWithOperatorOverloads() - { - var calculatedDimensions = Length.BaseDimensions / Duration.BaseDimensions; - Assert.True(calculatedDimensions == Speed.BaseDimensions); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnInstancePropertyWithOperatorOverloads() + public void TemperatureDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var length = Length.FromKilometers(100); - var duration = Duration.FromHours(1); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 5, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 6, 0, 0); - var calculatedDimensions = length.Dimensions / duration.Dimensions; - Assert.True(calculatedDimensions == Speed.BaseDimensions); - } + var result = baseDimensions1 * baseDimensions2; - [Fact] - public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnStaticPropertyWithOperatorOverloads() - { - var calculatedDimensions = Mass.BaseDimensions * Acceleration.BaseDimensions; - Assert.True(calculatedDimensions == Force.BaseDimensions); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 11); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnInstancePropertyWithOperatorOverloads() + public void TimeDimensionsDivideCorrectly() { - var mass = Mass.FromPounds(205); - var acceleration = Acceleration.FromMetersPerSecondSquared(9.8); + var baseDimensions1 = new BaseDimensions(0, 0, 6, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 5, 0, 0, 0, 0); - var calculatedDimensions = mass.Dimensions * acceleration.Dimensions; - Assert.True(calculatedDimensions == Force.BaseDimensions); - } + var result = baseDimensions1.Divide(baseDimensions2); - [Fact] - public void CheckToStringUsingMolarEntropy() - { - Assert.Equal("[Length]^2[Mass][Time]^-2[Temperature][Amount]", MolarEntropy.BaseDimensions.ToString()); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 1); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void GetHashCodeWorksProperly() + public void TimeDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var baseDimensions2 = new BaseDimensions(7, 6, 5, 4, 3, 2, 1); - var baseDimensions3 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - - var hashSet = new HashSet(); - - hashSet.Add(baseDimensions1); - Assert.Contains(baseDimensions1, hashSet); - - hashSet.Add(baseDimensions2); - Assert.Contains(baseDimensions2, hashSet); + var baseDimensions1 = new BaseDimensions(0, 0, 6, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 5, 0, 0, 0, 0); - // Should be the same as baseDimensions1 - Assert.Contains(baseDimensions3, hashSet); + var result = baseDimensions1 / baseDimensions2; - Assert.True(baseDimensions1.GetHashCode() != baseDimensions2.GetHashCode()); - Assert.True(baseDimensions1.GetHashCode() == baseDimensions3.GetHashCode()); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 1); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void DimensionlessPropertyIsCorrect() + public void TimeDimensionsMultiplyCorrectly() { - Assert.True(BaseDimensions.Dimensionless == new BaseDimensions(0, 0, 0, 0, 0, 0, 0)); + var baseDimensions1 = new BaseDimensions(0, 0, 3, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 4, 0, 0, 0, 0); + + var result = baseDimensions1.Multiply(baseDimensions2); + + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 7); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void IsDimensionlessMethodImplementedCorrectly() + public void TimeDimensionsMultiplyCorrectlyWithOperatorOverloads() { - Assert.True(BaseDimensions.Dimensionless.IsDimensionless()); - Assert.True(new BaseDimensions(0, 0, 0, 0, 0, 0, 0).IsDimensionless()); + var baseDimensions1 = new BaseDimensions(0, 0, 3, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 4, 0, 0, 0, 0); - Assert.False(BaseDimensions.Dimensionless.IsBaseQuantity()); - Assert.False(BaseDimensions.Dimensionless.IsDerivedQuantity()); + var result = baseDimensions1 * baseDimensions2; - // Example case - Assert.True(Level.BaseDimensions.IsDimensionless()); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 7); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); } } } diff --git a/UnitsNet.Tests/BaseUnitsTests.cs b/UnitsNet.Tests/BaseUnitsTests.cs index 3954e61b93..d34da832ea 100644 --- a/UnitsNet.Tests/BaseUnitsTests.cs +++ b/UnitsNet.Tests/BaseUnitsTests.cs @@ -9,13 +9,13 @@ namespace UnitsNet.Tests { public class BaseUnitsTests { - private static BaseUnits siBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + private static readonly BaseUnits siBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - private static BaseUnits siBaseUnitsCopy = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + private static readonly BaseUnits siBaseUnitsCopy = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - private static BaseUnits nonSiBaseUnits = new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, + private static readonly BaseUnits nonSiBaseUnits = new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); [Fact] @@ -34,13 +34,21 @@ public void ConstructorSetsUnitsProperly() } [Fact] - public void EqualsObjectIsImplementedCorrectly() + public void EqualityOperatorIsImplementedCorrectly() { - Assert.True(siBaseUnits.Equals((object)siBaseUnitsCopy)); - Assert.False(siBaseUnits.Equals((object)nonSiBaseUnits)); + Assert.True(siBaseUnits == siBaseUnitsCopy); + Assert.True(siBaseUnitsCopy == siBaseUnits); - Assert.False(siBaseUnits.Equals("Some object.")); - Assert.False(siBaseUnits.Equals((IFormatProvider)null)); + Assert.False(siBaseUnits == nonSiBaseUnits); + Assert.False(nonSiBaseUnits == siBaseUnits); + + Assert.False(siBaseUnits == null); + Assert.False(null == siBaseUnits); + + BaseUnits nullBaseUnits1 = null; + BaseUnits nullBaseUnits2 = null; + + Assert.True(nullBaseUnits1 == nullBaseUnits2); } [Fact] @@ -56,21 +64,26 @@ public void EqualsBaseUnitsIsImplementedCorrectly() } [Fact] - public void EqualityOperatorIsImplementedCorrectly() + public void EqualsObjectIsImplementedCorrectly() { - Assert.True(siBaseUnits == siBaseUnitsCopy); - Assert.True(siBaseUnitsCopy == siBaseUnits); + Assert.True(siBaseUnits.Equals((object) siBaseUnitsCopy)); + Assert.False(siBaseUnits.Equals((object) nonSiBaseUnits)); - Assert.False(siBaseUnits == nonSiBaseUnits); - Assert.False(nonSiBaseUnits == siBaseUnits); + Assert.False(siBaseUnits.Equals("Some object.")); + Assert.False(siBaseUnits.Equals((IFormatProvider) null)); + } - Assert.False(siBaseUnits == null); - Assert.False(null == siBaseUnits); + [Fact] + public void ExistsInWorksCorrectly() + { + Assert.False(BaseUnits.Undefined.IsSubsetOf(siBaseUnits)); + Assert.False(siBaseUnits.IsSubsetOf(BaseUnits.Undefined)); - BaseUnits nullBaseUnits1 = null; - BaseUnits nullBaseUnits2 = null; + var meterBaseUnits = new BaseUnits(LengthUnit.Meter); + Assert.True(meterBaseUnits.IsSubsetOf(siBaseUnits)); - Assert.True(nullBaseUnits1 == nullBaseUnits2); + // Not all units in siBaseUnits will exist in meterBaseUnits + Assert.False(siBaseUnits.IsSubsetOf(meterBaseUnits)); } [Fact] @@ -92,21 +105,43 @@ public void InequalityOperatorIsImplementedCorrectly() } [Fact] - public void UndefinedHasAllBaseUnitsAsUndefined() + public void IsFullyDefined_FalseIfAnyBaseUnitIsUndefined() { - Assert.Equal(LengthUnit.Undefined, BaseUnits.Undefined.Length); - Assert.Equal(MassUnit.Undefined, BaseUnits.Undefined.Mass); - Assert.Equal(DurationUnit.Undefined, BaseUnits.Undefined.Time); - Assert.Equal(ElectricCurrentUnit.Undefined, BaseUnits.Undefined.Current); - Assert.Equal(TemperatureUnit.Undefined, BaseUnits.Undefined.Temperature); - Assert.Equal(AmountOfSubstanceUnit.Undefined, BaseUnits.Undefined.Amount); - Assert.Equal(LuminousIntensityUnit.Undefined, BaseUnits.Undefined.LuminousIntensity); + Assert.False(new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, + current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(LengthUnit.Meter, time: DurationUnit.Second, + current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, + current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, amount: AmountOfSubstanceUnit.Mole, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole + ).IsFullyDefined); } [Fact] - public void UndefinedIsSubsetOfUndefined() + public void IsFullyDefined_TrueIfAllBaseUnitDefined() { - Assert.True(BaseUnits.Undefined.IsSubsetOf(BaseUnits.Undefined)); + Assert.True(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, + LuminousIntensityUnit.Candela).IsFullyDefined); } [Fact] @@ -115,19 +150,6 @@ public void IsSubsetOfReturnsFalseWithNull() Assert.False(siBaseUnits.IsSubsetOf(null)); } - [Fact] - public void ExistsInWorksCorrectly() - { - Assert.False(BaseUnits.Undefined.IsSubsetOf(siBaseUnits)); - Assert.False(siBaseUnits.IsSubsetOf(BaseUnits.Undefined)); - - var meterBaseUnits = new BaseUnits(LengthUnit.Meter); - Assert.True(meterBaseUnits.IsSubsetOf(siBaseUnits)); - - // Not all units in siBaseUnits will exist in meterBaseUnits - Assert.False(siBaseUnits.IsSubsetOf(meterBaseUnits)); - } - [Fact] public void ToStringGivesExpectedResult() { @@ -138,43 +160,21 @@ public void ToStringGivesExpectedResult() } [Fact] - public void IsFullyDefined_TrueIfAllBaseUnitDefined() + public void UndefinedHasAllBaseUnitsAsUndefined() { - Assert.True(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, - LuminousIntensityUnit.Candela).IsFullyDefined); + Assert.Equal(LengthUnit.Undefined, BaseUnits.Undefined.Length); + Assert.Equal(MassUnit.Undefined, BaseUnits.Undefined.Mass); + Assert.Equal(DurationUnit.Undefined, BaseUnits.Undefined.Time); + Assert.Equal(ElectricCurrentUnit.Undefined, BaseUnits.Undefined.Current); + Assert.Equal(TemperatureUnit.Undefined, BaseUnits.Undefined.Temperature); + Assert.Equal(AmountOfSubstanceUnit.Undefined, BaseUnits.Undefined.Amount); + Assert.Equal(LuminousIntensityUnit.Undefined, BaseUnits.Undefined.LuminousIntensity); } - + [Fact] - public void IsFullyDefined_FalseIfAnyBaseUnitIsUndefined() + public void UndefinedIsSubsetOfUndefined() { - Assert.False(new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, - current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, - current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, - current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, - temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, - current: ElectricCurrentUnit.Ampere, amount: AmountOfSubstanceUnit.Mole, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, - current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, - current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole - ).IsFullyDefined); + Assert.True(BaseUnits.Undefined.IsSubsetOf(BaseUnits.Undefined)); } } } diff --git a/UnitsNet.Tests/CustomCode/AccelerationTests.cs b/UnitsNet.Tests/CustomCode/AccelerationTests.cs index 30d4aafca0..b80b0936f6 100644 --- a/UnitsNet.Tests/CustomCode/AccelerationTests.cs +++ b/UnitsNet.Tests/CustomCode/AccelerationTests.cs @@ -36,7 +36,7 @@ public class AccelerationTests : AccelerationTestsBase [Fact] public void AccelerationTimesDensityEqualsSpecificWeight() { - SpecificWeight specificWeight = Acceleration.FromMetersPerSecondSquared(10) * Density.FromKilogramsPerCubicMeter(2); + var specificWeight = Acceleration.FromMetersPerSecondSquared(10) * Density.FromKilogramsPerCubicMeter(2); Assert.Equal(SpecificWeight.FromNewtonsPerCubicMeter(20), specificWeight); } } diff --git a/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs b/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs index e51ce88b3c..aa140c3be1 100644 --- a/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs @@ -18,13 +18,13 @@ public class AmplitudeRatioTests : AmplitudeRatioTestsBase protected override void AssertLogarithmicAddition() { - AmplitudeRatio v = AmplitudeRatio.FromDecibelVolts(40); + var v = AmplitudeRatio.FromDecibelVolts(40); AssertEx.EqualTolerance(46.0205999133, (v + v).DecibelVolts, DecibelVoltsTolerance); } protected override void AssertLogarithmicSubtraction() { - AmplitudeRatio v = AmplitudeRatio.FromDecibelVolts(40); + var v = AmplitudeRatio.FromDecibelVolts(40); AssertEx.EqualTolerance(46.6982292275, (AmplitudeRatio.FromDecibelVolts(50) - v).DecibelVolts, DecibelVoltsTolerance); } @@ -34,7 +34,7 @@ protected override void AssertLogarithmicSubtraction() [InlineData(-10)] public void InvalidVoltage_ExpectArgumentOutOfRangeException(double voltage) { - ElectricPotential invalidVoltage = ElectricPotential.FromVolts(voltage); + var invalidVoltage = ElectricPotential.FromVolts(voltage); // ReSharper disable once ObjectCreationAsStatement Assert.Throws(() => new AmplitudeRatio(invalidVoltage)); @@ -48,9 +48,9 @@ public void InvalidVoltage_ExpectArgumentOutOfRangeException(double voltage) public void ExpectVoltageConvertedToAmplitudeRatioCorrectly(double voltage, double expected) { // Amplitude ratio increases linearly by 20 dBV with power-of-10 increases of voltage. - ElectricPotential v = ElectricPotential.FromVolts(voltage); + var v = ElectricPotential.FromVolts(voltage); - double actual = AmplitudeRatio.FromElectricPotential(v).DecibelVolts; + var actual = AmplitudeRatio.FromElectricPotential(v).DecibelVolts; Assert.Equal(expected, actual); } @@ -63,9 +63,9 @@ public void ExpectVoltageConvertedToAmplitudeRatioCorrectly(double voltage, doub public void ExpectAmplitudeRatioConvertedToVoltageCorrectly(double amplitudeRatio, double expected) { // Voltage increases by powers of 10 for every 20 dBV increase in amplitude ratio. - AmplitudeRatio ar = AmplitudeRatio.FromDecibelVolts(amplitudeRatio); + var ar = AmplitudeRatio.FromDecibelVolts(amplitudeRatio); - double actual = ar.ToElectricPotential().Volts; + var actual = ar.ToElectricPotential().Volts; Assert.Equal(expected, actual); } @@ -78,9 +78,9 @@ public void ExpectAmplitudeRatioConvertedToVoltageCorrectly(double amplitudeRati [InlineData(60, 13.01)] public void AmplitudeRatioToPowerRatio_50OhmImpedance(double dBmV, double expected) { - AmplitudeRatio ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); + var ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); - double actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(50)).DecibelMilliwatts, 2); + var actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(50)).DecibelMilliwatts, 2); Assert.Equal(expected, actual); } @@ -91,9 +91,9 @@ public void AmplitudeRatioToPowerRatio_50OhmImpedance(double dBmV, double expect [InlineData(60, 11.25)] public void AmplitudeRatioToPowerRatio_75OhmImpedance(double dBmV, double expected) { - AmplitudeRatio ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); + var ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); - double actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(75)).DecibelMilliwatts, 2); + var actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(75)).DecibelMilliwatts, 2); Assert.Equal(expected, actual); } } diff --git a/UnitsNet.Tests/CustomCode/AngleTests.cs b/UnitsNet.Tests/CustomCode/AngleTests.cs index 1641165cce..b9b853e170 100644 --- a/UnitsNet.Tests/CustomCode/AngleTests.cs +++ b/UnitsNet.Tests/CustomCode/AngleTests.cs @@ -39,14 +39,14 @@ public class AngleTests : AngleTestsBase [Fact] public void AngleDividedByDurationEqualsRotationalSpeed() { - RotationalSpeed rotationalSpeed = Angle.FromRadians(10) / Duration.FromSeconds(5); + var rotationalSpeed = Angle.FromRadians(10) / Duration.FromSeconds(5); Assert.Equal(rotationalSpeed, RotationalSpeed.FromRadiansPerSecond(2)); } [Fact] public void AngleDividedByTimeSpanEqualsRotationalSpeed() { - RotationalSpeed rotationalSpeed = Angle.FromRadians(10) / TimeSpan.FromSeconds(5); + var rotationalSpeed = Angle.FromRadians(10) / TimeSpan.FromSeconds(5); Assert.Equal(rotationalSpeed, RotationalSpeed.FromRadiansPerSecond(2)); } } diff --git a/UnitsNet.Tests/CustomCode/AreaTests.cs b/UnitsNet.Tests/CustomCode/AreaTests.cs index d637cd18a9..bfefa947a1 100644 --- a/UnitsNet.Tests/CustomCode/AreaTests.cs +++ b/UnitsNet.Tests/CustomCode/AreaTests.cs @@ -8,12 +8,11 @@ namespace UnitsNet.Tests.CustomCode { public class AreaTests : AreaTestsBase { - protected override double SquareKilometersInOneSquareMeter => 1E-6; protected override double SquareMetersInOneSquareMeter => 1; - protected override double AcresInOneSquareMeter => 2.471053816137*1E-4; + protected override double AcresInOneSquareMeter => 2.471053816137 * 1E-4; protected override double HectaresInOneSquareMeter => 1E-4; @@ -29,7 +28,7 @@ public class AreaTests : AreaTestsBase protected override double SquareInchesInOneSquareMeter => 1550.003100; - protected override double SquareMilesInOneSquareMeter => 3.86102*1E-7; + protected override double SquareMilesInOneSquareMeter => 3.86102 * 1E-7; protected override double SquareYardsInOneSquareMeter => 1.19599; @@ -37,20 +36,6 @@ public class AreaTests : AreaTestsBase protected override double SquareNauticalMilesInOneSquareMeter => 0.00000029155335; - [Fact] - public void AreaDividedByLengthEqualsLength() - { - Length length = Area.FromSquareMeters(50)/Length.FromMeters(5); - Assert.Equal(length, Length.FromMeters(10)); - } - - [Fact] - public void AreaTimesMassFluxEqualsMassFlow() - { - MassFlow massFlow = Area.FromSquareMeters(20) * MassFlux.FromKilogramsPerSecondPerSquareMeter(2); - Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(40)); - } - [Theory] [InlineData(0, 0)] [InlineData(0.5, 0.19634954084936208)] @@ -58,9 +43,9 @@ public void AreaTimesMassFluxEqualsMassFlow() [InlineData(2, 3.141592653589793)] public void AreaFromCicleDiameterCalculatedCorrectly(double diameterMeters, double expected) { - Length diameter = Length.FromMeters(diameterMeters); + var diameter = Length.FromMeters(diameterMeters); - double actual = Area.FromCircleDiameter(diameter).SquareMeters; + var actual = Area.FromCircleDiameter(diameter).SquareMeters; Assert.Equal(expected, actual); } @@ -72,25 +57,32 @@ public void AreaFromCicleDiameterCalculatedCorrectly(double diameterMeters, doub [InlineData(2, 12.566370614359173)] public void AreaFromCicleRadiusCalculatedCorrectly(double radiusMeters, double expected) { - Length radius = Length.FromMeters(radiusMeters); + var radius = Length.FromMeters(radiusMeters); - double actual = Area.FromCircleRadius(radius).SquareMeters; + var actual = Area.FromCircleRadius(radius).SquareMeters; Assert.Equal(expected, actual); } [Fact] - public void AreaTimesSpeedEqualsVolumeFlow() + public void AreaDividedByLengthEqualsLength() { - VolumeFlow volumeFlow = Area.FromSquareMeters(20) * Speed.FromMetersPerSecond(2); - Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(40), volumeFlow); + var length = Area.FromSquareMeters(50) / Length.FromMeters(5); + Assert.Equal(length, Length.FromMeters(10)); } [Fact] - public void Constructor_UnitSystemSI_AssignsSIUnit() + public void AreaTimesMassFluxEqualsMassFlow() { - var area = new Area(1.0, UnitSystem.SI); - Assert.Equal(AreaUnit.SquareMeter, area.Unit); + var massFlow = Area.FromSquareMeters(20) * MassFlux.FromKilogramsPerSecondPerSquareMeter(2); + Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(40)); + } + + [Fact] + public void AreaTimesSpeedEqualsVolumeFlow() + { + var volumeFlow = Area.FromSquareMeters(20) * Speed.FromMetersPerSecond(2); + Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(40), volumeFlow); } [Fact] @@ -100,6 +92,13 @@ public void As_GivenSIUnitSystem_ReturnsSIValue() Assert.Equal(0.00129032, squareInches.As(UnitSystem.SI)); } + [Fact] + public void Constructor_UnitSystemSI_AssignsSIUnit() + { + var area = new Area(1.0, UnitSystem.SI); + Assert.Equal(AreaUnit.SquareMeter, area.Unit); + } + [Fact] public void ToUnit_GivenSIUnitSystem_ReturnsSIQuantity() { diff --git a/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs b/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs index ed637226a8..6e649a4824 100644 --- a/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs +++ b/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs @@ -1,7 +1,6 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using Xunit; namespace UnitsNet.Tests.CustomCode @@ -15,24 +14,24 @@ public class BrakeSpecificFuelConsumptionTests : BrakeSpecificFuelConsumptionTes protected override double PoundsPerMechanicalHorsepowerHourInOneKilogramPerJoule => 5918352.5016; [Fact] - public void PowerTimesBrakeSpecificFuelConsumptionEqualsMassFlow() + public void BrakeSpecificFuelConsumptionTimesSpecificEnergyEqualsEnergy() { - MassFlow massFlow = BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0) * Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0); - AssertEx.EqualTolerance(20.0, massFlow.TonnesPerDay, 1e-11); + var value = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); + Assert.Equal(200.0, value); } [Fact] public void DoubleDividedByBrakeSpecificFuelConsumptionEqualsSpecificEnergy() { - SpecificEnergy massFlow = 2.0 / BrakeSpecificFuelConsumption.FromKilogramsPerJoule(4.0); + var massFlow = 2.0 / BrakeSpecificFuelConsumption.FromKilogramsPerJoule(4.0); Assert.Equal(SpecificEnergy.FromJoulesPerKilogram(0.5), massFlow); } [Fact] - public void BrakeSpecificFuelConsumptionTimesSpecificEnergyEqualsEnergy() + public void PowerTimesBrakeSpecificFuelConsumptionEqualsMassFlow() { - double value = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); - Assert.Equal(200.0, value); + var massFlow = BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0) * Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0); + AssertEx.EqualTolerance(20.0, massFlow.TonnesPerDay, 1e-11); } } } diff --git a/UnitsNet.Tests/CustomCode/DensityTests.cs b/UnitsNet.Tests/CustomCode/DensityTests.cs index 6d70e059c2..796da4ad9e 100644 --- a/UnitsNet.Tests/CustomCode/DensityTests.cs +++ b/UnitsNet.Tests/CustomCode/DensityTests.cs @@ -88,38 +88,38 @@ public class DensityTests : DensityTestsBase protected override double KilogramsPerLiterInOneKilogramPerCubicMeter => 1e-3; [Fact] - public static void DensityTimesVolumeEqualsMass() - { - Mass mass = Density.FromKilogramsPerCubicMeter(2) * Volume.FromCubicMeters(3); - Assert.Equal(mass, Mass.FromKilograms(6)); - } - - [Fact] - public static void VolumeTimesDensityEqualsMass() + public void DensityTimesAccelerationEqualsSpecificWeight() { - Mass mass = Volume.FromCubicMeters(3) * Density.FromKilogramsPerCubicMeter(2); - Assert.Equal(mass, Mass.FromKilograms(6)); + var specificWeight = Density.FromKilogramsPerCubicMeter(10) * Acceleration.FromMetersPerSecondSquared(2); + Assert.Equal(SpecificWeight.FromNewtonsPerCubicMeter(20), specificWeight); } [Fact] public static void DensityTimesKinematicViscosityEqualsDynamicViscosity() { - DynamicViscosity dynamicViscosity = Density.FromKilogramsPerCubicMeter(2) * KinematicViscosity.FromSquareMetersPerSecond(10); + var dynamicViscosity = Density.FromKilogramsPerCubicMeter(2) * KinematicViscosity.FromSquareMetersPerSecond(10); Assert.Equal(dynamicViscosity, DynamicViscosity.FromNewtonSecondsPerMeterSquared(20)); } - + [Fact] public void DensityTimesSpeedEqualsMassFlux() { - MassFlux massFlux = Density.FromKilogramsPerCubicMeter(20) * Speed.FromMetersPerSecond(2); + var massFlux = Density.FromKilogramsPerCubicMeter(20) * Speed.FromMetersPerSecond(2); Assert.Equal(massFlux, MassFlux.FromKilogramsPerSecondPerSquareMeter(40)); } [Fact] - public void DensityTimesAccelerationEqualsSpecificWeight() + public static void DensityTimesVolumeEqualsMass() { - SpecificWeight specificWeight = Density.FromKilogramsPerCubicMeter(10) * Acceleration.FromMetersPerSecondSquared(2); - Assert.Equal(SpecificWeight.FromNewtonsPerCubicMeter(20), specificWeight); + var mass = Density.FromKilogramsPerCubicMeter(2) * Volume.FromCubicMeters(3); + Assert.Equal(mass, Mass.FromKilograms(6)); + } + + [Fact] + public static void VolumeTimesDensityEqualsMass() + { + var mass = Volume.FromCubicMeters(3) * Density.FromKilogramsPerCubicMeter(2); + Assert.Equal(mass, Mass.FromKilograms(6)); } } } diff --git a/UnitsNet.Tests/CustomCode/DurationTests.cs b/UnitsNet.Tests/CustomCode/DurationTests.cs index 4facb8eab1..d150a76d45 100644 --- a/UnitsNet.Tests/CustomCode/DurationTests.cs +++ b/UnitsNet.Tests/CustomCode/DurationTests.cs @@ -1,9 +1,9 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using Xunit; using System; using System.Globalization; +using Xunit; namespace UnitsNet.Tests.CustomCode { @@ -29,157 +29,157 @@ public class DurationTests : DurationTestsBase protected override double Years365InOneSecond => 3.170979198376458e-8; - [Fact] - public static void ToTimeSpanShouldThrowExceptionOnValuesLargerThanTimeSpanMax() + [Theory] + [InlineData("1s", 1)] + [InlineData("2 seconds", 2)] + [InlineData("1 ms", 1e-3)] + [InlineData("1000 msec", 1)] + [InlineData("1 с", 1, "ru-RU")] + [InlineData("1 сек", 1, "ru-RU")] + [InlineData("1000 мс", 1, "ru-RU")] + [InlineData("1000 мсек", 1, "ru-RU")] + public void DurationFromStringUsingMultipleAbbreviationsParsedCorrectly(string textValue, double expectedSeconds, string culture = null) { - Duration duration = Duration.FromSeconds(TimeSpan.MaxValue.TotalSeconds + 1); - Assert.Throws(() => duration.ToTimeSpan()); + var cultureInfo = culture == null ? null : new CultureInfo(culture); + + AssertEx.EqualTolerance(expectedSeconds, Duration.Parse(textValue, cultureInfo).Seconds, SecondsTolerance); } [Fact] - public static void ToTimeSpanShouldThrowExceptionOnValuesSmallerThanTimeSpanMin() + public static void DateTimeMinusDurationReturnsDateTime() { - Duration duration = Duration.FromSeconds(TimeSpan.MinValue.TotalSeconds - 1); - Assert.Throws(() => duration.ToTimeSpan()); + var dateTime = new DateTime(2016, 1, 2); + var oneDay = Duration.FromDays(1); + var result = dateTime - oneDay; + var expected = new DateTime(2016, 1, 1); + Assert.Equal(expected, result); } [Fact] - public static void ToTimeSpanShouldNotThrowExceptionOnValuesSlightlyLargerThanTimeSpanMin() + public static void DateTimePlusDurationReturnsDateTime() { - Duration duration = Duration.FromSeconds(TimeSpan.MinValue.TotalSeconds + 1); - TimeSpan timeSpan = duration.ToTimeSpan(); - AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-3); + var dateTime = new DateTime(2016, 1, 1); + var oneDay = Duration.FromDays(1); + var result = dateTime + oneDay; + var expected = new DateTime(2016, 1, 2); + Assert.Equal(expected, result); } [Fact] - public static void ToTimeSpanShouldNotThrowExceptionOnValuesSlightlySmallerThanTimeSpanMax() + public static void DurationGreaterThanOrEqualTimeSpanShouldReturnCorrectly() { - Duration duration = Duration.FromSeconds(TimeSpan.MaxValue.TotalSeconds - 1); - TimeSpan timeSpan = duration.ToTimeSpan(); - AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-3); + var timeSpan = TimeSpan.FromHours(11); + var duration = Duration.FromHours(12); + Assert.True(duration >= timeSpan, "duration should be greater than timeSpan"); } [Fact] - public static void ExplicitCastToTimeSpanShouldReturnSameValue() + public static void DurationGreaterThanTimeSpanShouldReturnCorrectly() { - Duration duration = Duration.FromSeconds(60); - TimeSpan timeSpan = (TimeSpan)duration; - AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-10); + var timeSpan = TimeSpan.FromHours(11); + var duration = Duration.FromHours(12); + Assert.True(duration > timeSpan, "duration should be greater than timeSpan"); } [Fact] - public static void ExplicitCastToDurationShouldReturnSameValue() + public static void DurationLessThanOrEqualTimeSpanShouldReturnCorrectly() { - TimeSpan timeSpan = TimeSpan.FromSeconds(60); - Duration duration = (Duration)timeSpan; - AssertEx.EqualTolerance(timeSpan.TotalSeconds, duration.Seconds, 1e-10); + var timeSpan = TimeSpan.FromHours(11); + var duration = Duration.FromHours(10); + Assert.True(duration <= timeSpan, "duration should be less than timeSpan"); } [Fact] - public static void DateTimePlusDurationReturnsDateTime() + public static void DurationLessThanTimeSpanShouldReturnCorrectly() { - DateTime dateTime = new DateTime(2016, 1, 1); - Duration oneDay = Duration.FromDays(1); - DateTime result = dateTime + oneDay; - DateTime expected = new DateTime(2016, 1, 2); - Assert.Equal(expected, result); + var timeSpan = TimeSpan.FromHours(11); + var duration = Duration.FromHours(10); + Assert.True(duration < timeSpan, "duration should be less than timeSpan"); } [Fact] - public static void DateTimeMinusDurationReturnsDateTime() + public void DurationTimesVolumeFlowEqualsVolume() { - DateTime dateTime = new DateTime(2016, 1, 2); - Duration oneDay = Duration.FromDays(1); - DateTime result = dateTime - oneDay; - DateTime expected = new DateTime(2016, 1, 1); - Assert.Equal(expected, result); + var volume = Duration.FromSeconds(20) * VolumeFlow.FromCubicMetersPerSecond(2); + Assert.Equal(Volume.FromCubicMeters(40), volume); } [Fact] - public static void TimeSpanLessThanDurationShouldReturnCorrectly() + public static void ExplicitCastToDurationShouldReturnSameValue() { - TimeSpan timeSpan = TimeSpan.FromHours(10); - Duration duration = Duration.FromHours(11); - Assert.True(timeSpan < duration, "timeSpan should be less than duration"); + var timeSpan = TimeSpan.FromSeconds(60); + var duration = (Duration) timeSpan; + AssertEx.EqualTolerance(timeSpan.TotalSeconds, duration.Seconds, 1e-10); } [Fact] - public static void TimeSpanGreaterThanDurationShouldReturnCorrectly() + public static void ExplicitCastToTimeSpanShouldReturnSameValue() { - TimeSpan timeSpan = TimeSpan.FromHours(12); - Duration duration = Duration.FromHours(11); - Assert.True(timeSpan > duration, "timeSpan should be greater than duration"); + var duration = Duration.FromSeconds(60); + var timeSpan = (TimeSpan) duration; + AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-10); } [Fact] - public static void DurationLessThanTimeSpanShouldReturnCorrectly() + public static void TimeSpanGreaterThanDurationShouldReturnCorrectly() { - TimeSpan timeSpan = TimeSpan.FromHours(11); - Duration duration = Duration.FromHours(10); - Assert.True(duration < timeSpan, "duration should be less than timeSpan"); + var timeSpan = TimeSpan.FromHours(12); + var duration = Duration.FromHours(11); + Assert.True(timeSpan > duration, "timeSpan should be greater than duration"); } [Fact] - public static void DurationGreaterThanTimeSpanShouldReturnCorrectly() + public static void TimeSpanGreaterThanOrEqualDurationShouldReturnCorrectly() { - TimeSpan timeSpan = TimeSpan.FromHours(11); - Duration duration = Duration.FromHours(12); - Assert.True(duration > timeSpan, "duration should be greater than timeSpan"); + var timeSpan = TimeSpan.FromHours(12); + var duration = Duration.FromHours(11); + Assert.True(timeSpan >= duration, "timeSpan should be greater than duration"); } [Fact] public static void TimeSpanLessOrEqualThanDurationShouldReturnCorrectly() { - TimeSpan timeSpan = TimeSpan.FromHours(10); - Duration duration = Duration.FromHours(11); + var timeSpan = TimeSpan.FromHours(10); + var duration = Duration.FromHours(11); Assert.True(timeSpan <= duration, "timeSpan should be less than duration"); } [Fact] - public static void TimeSpanGreaterThanOrEqualDurationShouldReturnCorrectly() + public static void TimeSpanLessThanDurationShouldReturnCorrectly() { - TimeSpan timeSpan = TimeSpan.FromHours(12); - Duration duration = Duration.FromHours(11); - Assert.True(timeSpan >= duration, "timeSpan should be greater than duration"); + var timeSpan = TimeSpan.FromHours(10); + var duration = Duration.FromHours(11); + Assert.True(timeSpan < duration, "timeSpan should be less than duration"); } [Fact] - public static void DurationLessThanOrEqualTimeSpanShouldReturnCorrectly() + public static void ToTimeSpanShouldNotThrowExceptionOnValuesSlightlyLargerThanTimeSpanMin() { - TimeSpan timeSpan = TimeSpan.FromHours(11); - Duration duration = Duration.FromHours(10); - Assert.True(duration <= timeSpan, "duration should be less than timeSpan"); + var duration = Duration.FromSeconds(TimeSpan.MinValue.TotalSeconds + 1); + var timeSpan = duration.ToTimeSpan(); + AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-3); } [Fact] - public static void DurationGreaterThanOrEqualTimeSpanShouldReturnCorrectly() + public static void ToTimeSpanShouldNotThrowExceptionOnValuesSlightlySmallerThanTimeSpanMax() { - TimeSpan timeSpan = TimeSpan.FromHours(11); - Duration duration = Duration.FromHours(12); - Assert.True(duration >= timeSpan, "duration should be greater than timeSpan"); + var duration = Duration.FromSeconds(TimeSpan.MaxValue.TotalSeconds - 1); + var timeSpan = duration.ToTimeSpan(); + AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-3); } [Fact] - public void DurationTimesVolumeFlowEqualsVolume() + public static void ToTimeSpanShouldThrowExceptionOnValuesLargerThanTimeSpanMax() { - Volume volume = Duration.FromSeconds(20) * VolumeFlow.FromCubicMetersPerSecond(2); - Assert.Equal(Volume.FromCubicMeters(40), volume); + var duration = Duration.FromSeconds(TimeSpan.MaxValue.TotalSeconds + 1); + Assert.Throws(() => duration.ToTimeSpan()); } - [Theory] - [InlineData("1s", 1)] - [InlineData("2 seconds", 2)] - [InlineData("1 ms", 1e-3)] - [InlineData("1000 msec", 1)] - [InlineData("1 с", 1, "ru-RU")] - [InlineData("1 сек", 1, "ru-RU")] - [InlineData("1000 мс", 1, "ru-RU")] - [InlineData("1000 мсек", 1, "ru-RU")] - public void DurationFromStringUsingMultipleAbbreviationsParsedCorrectly(string textValue, double expectedSeconds, string culture = null) + [Fact] + public static void ToTimeSpanShouldThrowExceptionOnValuesSmallerThanTimeSpanMin() { - var cultureInfo = culture == null ? null : new CultureInfo(culture); - - AssertEx.EqualTolerance(expectedSeconds, Duration.Parse(textValue, cultureInfo).Seconds, SecondsTolerance); + var duration = Duration.FromSeconds(TimeSpan.MinValue.TotalSeconds - 1); + Assert.Throws(() => duration.ToTimeSpan()); } } } diff --git a/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs b/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs index df79561f7f..bf03ee2ea8 100644 --- a/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs +++ b/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs @@ -1,7 +1,6 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using Xunit; namespace UnitsNet.Tests.CustomCode @@ -21,7 +20,7 @@ public class DynamicViscosityTests : DynamicViscosityTestsBase [Fact] public static void DynamicViscosityDividedByDensityEqualsKinematicViscosity() { - KinematicViscosity kinematicViscosity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(10) / Density.FromKilogramsPerCubicMeter(2); + var kinematicViscosity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(10) / Density.FromKilogramsPerCubicMeter(2); Assert.Equal(kinematicViscosity, KinematicViscosity.FromSquareMetersPerSecond(5)); } } diff --git a/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs b/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs index 339b51ef65..66bb6c89bc 100644 --- a/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs @@ -31,7 +31,7 @@ public class ElectricCurrentTests : ElectricCurrentTestsBase [InlineData(-10, -2, 20)] public void ElectricCurrentTimesElectricResistanceEqualsElectricPotential(float current, float resistance, float expected) { - ElectricPotential potential = ElectricCurrent.FromAmperes(current) * ElectricResistance.FromOhms(resistance); + var potential = ElectricCurrent.FromAmperes(current) * ElectricResistance.FromOhms(resistance); Assert.Equal(expected, potential.Volts); } } diff --git a/UnitsNet.Tests/CustomCode/ElectricPotentialTests.cs b/UnitsNet.Tests/CustomCode/ElectricPotentialTests.cs index 4e27fe901e..44e3851f90 100644 --- a/UnitsNet.Tests/CustomCode/ElectricPotentialTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricPotentialTests.cs @@ -25,7 +25,7 @@ public class ElectricPotentialTests : ElectricPotentialTestsBase [InlineData(-10, -2, 5)] public void ElectricPotentialDividedByElectricCurrentEqualsElectricResistance(float potential, float current, float expected) { - ElectricResistance resistance = ElectricPotential.FromVolts(potential) / ElectricCurrent.FromAmperes(current); + var resistance = ElectricPotential.FromVolts(potential) / ElectricCurrent.FromAmperes(current); Assert.Equal(expected, resistance.Ohms); } @@ -37,7 +37,7 @@ public void ElectricPotentialDividedByElectricCurrentEqualsElectricResistance(fl [InlineData(-10, -2, 5)] public void ElectricPotentialDividedByElectricResistanceEqualsElectricCurrent(float potential, float resistance, float expected) { - ElectricCurrent current = ElectricPotential.FromVolts(potential) / ElectricResistance.FromOhms(resistance); + var current = ElectricPotential.FromVolts(potential) / ElectricResistance.FromOhms(resistance); Assert.Equal(expected, current.Amperes); } } diff --git a/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs b/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs index bfa15c50bf..498e2aa53d 100644 --- a/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs @@ -25,7 +25,7 @@ public class ElectricResistanceTests : ElectricResistanceTestsBase [InlineData(-10, -2, 20)] public void ElectricResistanceTimesElectricCurrentEqualsElectricPotential(float resistance, float current, float expected) { - ElectricPotential potential = ElectricResistance.FromOhms(resistance) * ElectricCurrent.FromAmperes(current) ; + var potential = ElectricResistance.FromOhms(resistance) * ElectricCurrent.FromAmperes(current); Assert.Equal(expected, potential.Volts); } } diff --git a/UnitsNet.Tests/CustomCode/EnergyTests.cs b/UnitsNet.Tests/CustomCode/EnergyTests.cs index 40c00b6547..f5ac7e065a 100644 --- a/UnitsNet.Tests/CustomCode/EnergyTests.cs +++ b/UnitsNet.Tests/CustomCode/EnergyTests.cs @@ -61,17 +61,17 @@ public class EnergyTests : EnergyTestsBase protected override double WattHoursInOneJoule => 0.000277777778; [Fact] - public void Constructor_UnitSystemSI_AssignsSIUnit() + public void As_GivenSIUnitSystem_ReturnsSIValue() { - var energy = new Energy(1.0, UnitSystem.SI); - Assert.Equal(EnergyUnit.Joule, energy.Unit); + var btus = new Energy(2.0, EnergyUnit.BritishThermalUnit); + Assert.Equal(2110.11170524, btus.As(UnitSystem.SI)); } [Fact] - public void As_GivenSIUnitSystem_ReturnsSIValue() + public void Constructor_UnitSystemSI_AssignsSIUnit() { - var btus = new Energy(2.0, EnergyUnit.BritishThermalUnit); - Assert.Equal(2110.11170524, btus.As(UnitSystem.SI)); + var energy = new Energy(1.0, UnitSystem.SI); + Assert.Equal(EnergyUnit.Joule, energy.Unit); } [Fact] diff --git a/UnitsNet.Tests/CustomCode/ForceTests.cs b/UnitsNet.Tests/CustomCode/ForceTests.cs index 34b620ffb7..48180f7505 100644 --- a/UnitsNet.Tests/CustomCode/ForceTests.cs +++ b/UnitsNet.Tests/CustomCode/ForceTests.cs @@ -32,58 +32,58 @@ public class ForceTests : ForceTestsBase protected override double OunceForceInOneNewton => 3.596943089595368; [Fact] - public void ForceDividedByAreaEqualsPressure() + public void ForceDividedByAccelerationEqualsMass() { - Pressure pressure = Force.FromNewtons(90)/Area.FromSquareMeters(9); - Assert.Equal(pressure, Pressure.FromNewtonsPerSquareMeter(10)); + var acceleration = Force.FromNewtons(200) / Acceleration.FromMetersPerSecondSquared(50); + Assert.Equal(acceleration, Mass.FromKilograms(4)); } [Fact] - public void PressureByAreaEqualsForce() + public void ForceDividedByAreaEqualsPressure() { - Force force = Force.FromPressureByArea(Pressure.FromNewtonsPerSquareMeter(5), Area.FromSquareMeters(7)); - Assert.Equal(force, Force.FromNewtons(35)); + var pressure = Force.FromNewtons(90) / Area.FromSquareMeters(9); + Assert.Equal(pressure, Pressure.FromNewtonsPerSquareMeter(10)); } [Fact] - public void ForceDividedByMassEqualsAcceleration() + public void ForceDividedByLengthEqualsForcePerLength() { - Acceleration acceleration = Force.FromNewtons(27)/Mass.FromKilograms(9); - Assert.Equal(acceleration, Acceleration.FromMetersPerSecondSquared(3)); + var forcePerLength = Force.FromNewtons(200) / Length.FromMeters(50); + Assert.Equal(forcePerLength, ForcePerLength.FromNewtonsPerMeter(4)); } [Fact] - public void ForceDividedByAccelerationEqualsMass() + public void ForceDividedByMassEqualsAcceleration() { - Mass acceleration = Force.FromNewtons(200)/Acceleration.FromMetersPerSecondSquared(50); - Assert.Equal(acceleration, Mass.FromKilograms(4)); + var acceleration = Force.FromNewtons(27) / Mass.FromKilograms(9); + Assert.Equal(acceleration, Acceleration.FromMetersPerSecondSquared(3)); } [Fact] - public void ForceDividedByLengthEqualsForcePerLength() + public void ForceTimesSpeedEqualsPower() { - ForcePerLength forcePerLength = Force.FromNewtons(200) / Length.FromMeters(50); - Assert.Equal(forcePerLength, ForcePerLength.FromNewtonsPerMeter(4)); + var power = Force.FromNewtons(27.0) * Speed.FromMetersPerSecond(10.0); + Assert.Equal(power, Power.FromWatts(270)); } [Fact] public void MassByAccelerationEqualsForce() { - Force force = Force.FromMassByAcceleration(Mass.FromKilograms(85), Acceleration.FromMetersPerSecondSquared(-4)); + var force = Force.FromMassByAcceleration(Mass.FromKilograms(85), Acceleration.FromMetersPerSecondSquared(-4)); Assert.Equal(force, Force.FromNewtons(-340)); } [Fact] - public void ForceTimesSpeedEqualsPower() + public void PressureByAreaEqualsForce() { - Power power = Force.FromNewtons(27.0)*Speed.FromMetersPerSecond(10.0); - Assert.Equal(power, Power.FromWatts(270)); + var force = Force.FromPressureByArea(Pressure.FromNewtonsPerSquareMeter(5), Area.FromSquareMeters(7)); + Assert.Equal(force, Force.FromNewtons(35)); } [Fact] public void SpeedTimesForceEqualsPower() { - Power power = Speed.FromMetersPerSecond(10.0)*Force.FromNewtons(27.0); + var power = Speed.FromMetersPerSecond(10.0) * Force.FromNewtons(27.0); Assert.Equal(power, Power.FromWatts(270)); } } diff --git a/UnitsNet.Tests/CustomCode/FrequencyTests.cs b/UnitsNet.Tests/CustomCode/FrequencyTests.cs index 41253fe566..7560e91bf5 100644 --- a/UnitsNet.Tests/CustomCode/FrequencyTests.cs +++ b/UnitsNet.Tests/CustomCode/FrequencyTests.cs @@ -21,7 +21,7 @@ public class FrequencyTests : FrequencyTestsBase protected override double CyclesPerMinuteInOneHertz => 60; - protected override double RadiansPerSecondInOneHertz => 2*Math.PI; + protected override double RadiansPerSecondInOneHertz => 2 * Math.PI; protected override double BeatsPerMinuteInOneHertz => 60; } diff --git a/UnitsNet.Tests/CustomCode/IQuantityTests.cs b/UnitsNet.Tests/CustomCode/IQuantityTests.cs index 9eda6cd2e8..80ce2d6347 100644 --- a/UnitsNet.Tests/CustomCode/IQuantityTests.cs +++ b/UnitsNet.Tests/CustomCode/IQuantityTests.cs @@ -9,18 +9,11 @@ namespace UnitsNet.Tests { public partial class IQuantityTests { - [Fact] - public void As_GivenWrongUnitType_ThrowsArgumentException() - { - IQuantity length = Length.FromMeters(1.2345); - Assert.Throws(() => length.As(MassUnit.Kilogram)); - } - [Fact] public void As_GivenNullUnitSystem_ThrowsArgumentNullException() { IQuantity imperialLengthQuantity = new Length(2.0, LengthUnit.Inch); - Assert.Throws(() => imperialLengthQuantity.As((UnitSystem)null)); + Assert.Throws(() => imperialLengthQuantity.As((UnitSystem) null)); } [Fact] @@ -31,17 +24,17 @@ public void As_GivenSIUnitSystem_ReturnsSIValue() } [Fact] - public void ToUnit_GivenWrongUnitType_ThrowsArgumentException() + public void As_GivenWrongUnitType_ThrowsArgumentException() { IQuantity length = Length.FromMeters(1.2345); - Assert.Throws(() => length.ToUnit(MassUnit.Kilogram)); + Assert.Throws(() => length.As(MassUnit.Kilogram)); } [Fact] public void ToUnit_GivenNullUnitSystem_ThrowsArgumentNullException() { IQuantity imperialLengthQuantity = new Length(2.0, LengthUnit.Inch); - Assert.Throws(() => imperialLengthQuantity.ToUnit((UnitSystem)null)); + Assert.Throws(() => imperialLengthQuantity.ToUnit((UnitSystem) null)); } [Fact] @@ -49,10 +42,17 @@ public void ToUnit_GivenSIUnitSystem_ReturnsSIQuantity() { IQuantity inches = new Length(2.0, LengthUnit.Inch); - IQuantity inSI = inches.ToUnit(UnitSystem.SI); + var inSI = inches.ToUnit(UnitSystem.SI); Assert.Equal(0.0508, inSI.Value); Assert.Equal(LengthUnit.Meter, inSI.Unit); } + + [Fact] + public void ToUnit_GivenWrongUnitType_ThrowsArgumentException() + { + IQuantity length = Length.FromMeters(1.2345); + Assert.Throws(() => length.ToUnit(MassUnit.Kilogram)); + } } } diff --git a/UnitsNet.Tests/CustomCode/InformationTests.cs b/UnitsNet.Tests/CustomCode/InformationTests.cs index 2a7383e8cc..4cf999642b 100644 --- a/UnitsNet.Tests/CustomCode/InformationTests.cs +++ b/UnitsNet.Tests/CustomCode/InformationTests.cs @@ -14,58 +14,51 @@ public class InformationTests : InformationTestsBase protected override double ExabitsInOneBit => 1e-18d; - protected override double ExabytesInOneBit => 0.125d*1e-18d; + protected override double ExabytesInOneBit => 0.125d * 1e-18d; - protected override double ExbibitsInOneBit => 1d/Math.Pow(1024, 6); + protected override double ExbibitsInOneBit => 1d / Math.Pow(1024, 6); - protected override double ExbibytesInOneBit => 1/8d/Math.Pow(1024, 6); + protected override double ExbibytesInOneBit => 1 / 8d / Math.Pow(1024, 6); - protected override double GibibitsInOneBit => 1d/Math.Pow(1024, 3); + protected override double GibibitsInOneBit => 1d / Math.Pow(1024, 3); - protected override double GibibytesInOneBit => 1d/8/Math.Pow(1024, 3); + protected override double GibibytesInOneBit => 1d / 8 / Math.Pow(1024, 3); protected override double GigabitsInOneBit => 1e-9d; - protected override double GigabytesInOneBit => 0.125d*1e-9d; + protected override double GigabytesInOneBit => 0.125d * 1e-9d; - protected override double KibibitsInOneBit => 1d/1024d; + protected override double KibibitsInOneBit => 1d / 1024d; - protected override double KibibytesInOneBit => 1d/8/1024d; + protected override double KibibytesInOneBit => 1d / 8 / 1024d; protected override double KilobitsInOneBit => 0.001d; protected override double KilobytesInOneBit => 0.000125d; - protected override double MebibitsInOneBit => 1d/Math.Pow(1024, 2); + protected override double MebibitsInOneBit => 1d / Math.Pow(1024, 2); - protected override double MebibytesInOneBit => 1d/8/Math.Pow(1024, 2); + protected override double MebibytesInOneBit => 1d / 8 / Math.Pow(1024, 2); protected override double MegabitsInOneBit => 1e-6d; - protected override double MegabytesInOneBit => 0.125d*1e-6d; + protected override double MegabytesInOneBit => 0.125d * 1e-6d; - protected override double PebibitsInOneBit => 1d/Math.Pow(1024, 5); + protected override double PebibitsInOneBit => 1d / Math.Pow(1024, 5); - protected override double PebibytesInOneBit => 1d/8/Math.Pow(1024, 5); + protected override double PebibytesInOneBit => 1d / 8 / Math.Pow(1024, 5); protected override double PetabitsInOneBit => 1e-15d; - protected override double PetabytesInOneBit => 0.125d*1e-15d; + protected override double PetabytesInOneBit => 0.125d * 1e-15d; - protected override double TebibitsInOneBit => 1d/Math.Pow(1024, 4); + protected override double TebibitsInOneBit => 1d / Math.Pow(1024, 4); - protected override double TebibytesInOneBit => 1d/8/Math.Pow(1024, 4); + protected override double TebibytesInOneBit => 1d / 8 / Math.Pow(1024, 4); protected override double TerabitsInOneBit => 1e-12d; - protected override double TerabytesInOneBit => 0.125d*1e-12d; - -// ReSharper disable once InconsistentNaming - [Fact] - public void OneKBHas1000Bytes() - { - Assert.Equal(1000, Information.FromKilobytes(1).Bytes); - } + protected override double TerabytesInOneBit => 0.125d * 1e-12d; [Fact] public void MaxValueIsCorrectForUnitWithBaseTypeDecimal() @@ -78,5 +71,12 @@ public void MinValueIsCorrectForUnitWithBaseTypeDecimal() { Assert.Equal((double) decimal.MinValue, Information.MinValue.Bits); } + +// ReSharper disable once InconsistentNaming + [Fact] + public void OneKBHas1000Bytes() + { + Assert.Equal(1000, Information.FromKilobytes(1).Bytes); + } } } diff --git a/UnitsNet.Tests/CustomCode/KinematicViscosityTests.cs b/UnitsNet.Tests/CustomCode/KinematicViscosityTests.cs index f41e2d5d54..5ec32cdc9a 100644 --- a/UnitsNet.Tests/CustomCode/KinematicViscosityTests.cs +++ b/UnitsNet.Tests/CustomCode/KinematicViscosityTests.cs @@ -27,43 +27,43 @@ public class KinematicViscosityTests : KinematicViscosityTestsBase [Fact] public static void DurationTimesKinematicViscosityEqualsArea() { - Area area = Duration.FromSeconds(2)*KinematicViscosity.FromSquareMetersPerSecond(4); + var area = Duration.FromSeconds(2) * KinematicViscosity.FromSquareMetersPerSecond(4); Assert.Equal(area, Area.FromSquareMeters(8)); } [Fact] public static void KinematicViscosityDividedByLengthEqualsSpeed() { - Speed speed = KinematicViscosity.FromSquareMetersPerSecond(4)/Length.FromMeters(2); + var speed = KinematicViscosity.FromSquareMetersPerSecond(4) / Length.FromMeters(2); Assert.Equal(speed, Speed.FromMetersPerSecond(2)); } [Fact] - public static void KinematicViscosityTimesDurationEqualsArea() + public static void KinematicViscosityTimesDensityEqualsDynamicViscosity() { - Area area = KinematicViscosity.FromSquareMetersPerSecond(4)*Duration.FromSeconds(2); - Assert.Equal(area, Area.FromSquareMeters(8)); + var dynamicViscosity = KinematicViscosity.FromSquareMetersPerSecond(10) * Density.FromKilogramsPerCubicMeter(2); + Assert.Equal(dynamicViscosity, DynamicViscosity.FromNewtonSecondsPerMeterSquared(20)); } [Fact] - public static void KinematicViscosityTimesTimeSpanEqualsArea() + public static void KinematicViscosityTimesDurationEqualsArea() { - Area area = KinematicViscosity.FromSquareMetersPerSecond(4)*TimeSpan.FromSeconds(2); + var area = KinematicViscosity.FromSquareMetersPerSecond(4) * Duration.FromSeconds(2); Assert.Equal(area, Area.FromSquareMeters(8)); } [Fact] - public static void TimeSpanTimesKinematicViscosityEqualsArea() + public static void KinematicViscosityTimesTimeSpanEqualsArea() { - Area area = TimeSpan.FromSeconds(2)*KinematicViscosity.FromSquareMetersPerSecond(4); + var area = KinematicViscosity.FromSquareMetersPerSecond(4) * TimeSpan.FromSeconds(2); Assert.Equal(area, Area.FromSquareMeters(8)); } [Fact] - public static void KinematicViscosityTimesDensityEqualsDynamicViscosity() + public static void TimeSpanTimesKinematicViscosityEqualsArea() { - DynamicViscosity dynamicViscosity = KinematicViscosity.FromSquareMetersPerSecond(10) * Density.FromKilogramsPerCubicMeter(2); - Assert.Equal(dynamicViscosity, DynamicViscosity.FromNewtonSecondsPerMeterSquared(20)); + var area = TimeSpan.FromSeconds(2) * KinematicViscosity.FromSquareMetersPerSecond(4); + Assert.Equal(area, Area.FromSquareMeters(8)); } } } diff --git a/UnitsNet.Tests/CustomCode/KnownQuantities.cs b/UnitsNet.Tests/CustomCode/KnownQuantities.cs index 0a3b8a9b37..8469efab84 100644 --- a/UnitsNet.Tests/CustomCode/KnownQuantities.cs +++ b/UnitsNet.Tests/CustomCode/KnownQuantities.cs @@ -1,4 +1,7 @@ -namespace UnitsNet.Tests.CustomCode +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +namespace UnitsNet.Tests.CustomCode { public static class KnownQuantities { diff --git a/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs b/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs index c07c02af5f..fb835ae18d 100644 --- a/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs +++ b/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs @@ -12,23 +12,6 @@ public class FeetInchesTests private const double FeetTolerance = 1e-5; private const double InchesTolerance = 1e-5; - [Fact] - public void FeetInchesFrom() - { - Length meter = Length.FromFeetInches(2, 3); - double expectedMeters = 2/FeetInOneMeter + 3/InchesInOneMeter; - AssertEx.EqualTolerance(expectedMeters, meter.Meters, FeetTolerance); - } - - [Fact] - public void FeetInchesRoundTrip() - { - Length meter = Length.FromFeetInches(2, 3); - FeetInches feetInches = meter.FeetInches; - AssertEx.EqualTolerance(2, feetInches.Feet, FeetTolerance); - AssertEx.EqualTolerance(3, feetInches.Inches, InchesTolerance); - } - [Theory] [InlineData("1'", 1)] // Feet only [InlineData("1′", 1)] // Feet only @@ -62,7 +45,7 @@ public void FeetInchesRoundTrip() [InlineData("-1ft 1in", -1.08333333)] public void TryParseFeetInches(string str, double expectedFeet) { - Assert.True(Length.TryParseFeetInches(str, out Length result)); + Assert.True(Length.TryParseFeetInches(str, out var result)); AssertEx.EqualTolerance(expectedFeet, result.Feet, 1e-5); } @@ -85,8 +68,25 @@ public void TryParseFeetInches(string str, double expectedFeet) [InlineData("1'1`")] public void TryParseFeetInches_GivenInvalidString_ReturnsFalseAndZeroOut(string str) { - Assert.False(Length.TryParseFeetInches(str, out Length result)); + Assert.False(Length.TryParseFeetInches(str, out var result)); Assert.Equal(Length.Zero, result); } + + [Fact] + public void FeetInchesFrom() + { + var meter = Length.FromFeetInches(2, 3); + var expectedMeters = 2 / FeetInOneMeter + 3 / InchesInOneMeter; + AssertEx.EqualTolerance(expectedMeters, meter.Meters, FeetTolerance); + } + + [Fact] + public void FeetInchesRoundTrip() + { + var meter = Length.FromFeetInches(2, 3); + var feetInches = meter.FeetInches; + AssertEx.EqualTolerance(2, feetInches.Feet, FeetTolerance); + AssertEx.EqualTolerance(3, feetInches.Inches, InchesTolerance); + } } } diff --git a/UnitsNet.Tests/CustomCode/LengthTests.cs b/UnitsNet.Tests/CustomCode/LengthTests.cs index d5dc4f4d8e..fef6177f2c 100644 --- a/UnitsNet.Tests/CustomCode/LengthTests.cs +++ b/UnitsNet.Tests/CustomCode/LengthTests.cs @@ -1,9 +1,9 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using Xunit; -using UnitsNet.Units; using System; +using UnitsNet.Units; +using Xunit; namespace UnitsNet.Tests.CustomCode { @@ -53,7 +53,7 @@ public class LengthTests : LengthTestsBase protected override double ShacklesInOneMeter => 0.0364538; - protected override double NauticalMilesInOneMeter => 1.0/1852.0; + protected override double NauticalMilesInOneMeter => 1.0 / 1852.0; protected override double HandsInOneMeter => 9.8425196850393701; @@ -73,76 +73,87 @@ public class LengthTests : LengthTestsBase protected override double SolarRadiusesInOneMeter => 1.43779384911791000E-09; - [ Fact] + [Fact] public void AreaTimesLengthEqualsVolume() { - Volume volume = Area.FromSquareMeters(10)*Length.FromMeters(3); + var volume = Area.FromSquareMeters(10) * Length.FromMeters(3); Assert.Equal(volume, Volume.FromCubicMeters(30)); } [Fact] - public void ForceTimesLengthEqualsTorque() + public void As_GivenSIUnitSystem_ReturnsSIValue() { - Torque torque = Force.FromNewtons(1)*Length.FromMeters(3); - Assert.Equal(torque, Torque.FromNewtonMeters(3)); + var inches = new Length(2.0, LengthUnit.Inch); + Assert.Equal(0.0508, inches.As(UnitSystem.SI)); } [Fact] - public void LengthTimesAreaEqualsVolume() + public void Constructor_UnitSystemNull_ThrowsArgumentNullException() { - Volume volume = Length.FromMeters(3)*Area.FromSquareMeters(9); - Assert.Equal(volume, Volume.FromCubicMeters(27)); + Assert.Throws(() => new Length(1.0, null)); } [Fact] - public void LengthTimesForceEqualsTorque() + public void Constructor_UnitSystemSI_AssignsSIUnit() { - Torque torque = Length.FromMeters(3)*Force.FromNewtons(1); - Assert.Equal(torque, Torque.FromNewtonMeters(3)); + var length = new Length(1.0, UnitSystem.SI); + Assert.Equal(LengthUnit.Meter, length.Unit); } [Fact] - public void LengthTimesLengthEqualsArea() + public void Constructor_UnitSystemWithNoMatchingBaseUnits_ThrowsArgumentException() { - Area area = Length.FromMeters(10)*Length.FromMeters(2); - Assert.Equal(area, Area.FromSquareMeters(20)); + // AmplitudeRatio is unitless. Can't have any matches :) + Assert.Throws(() => new AmplitudeRatio(1.0, UnitSystem.SI)); + } + + [Fact] + public void ForceTimesLengthEqualsTorque() + { + var torque = Force.FromNewtons(1) * Length.FromMeters(3); + Assert.Equal(torque, Torque.FromNewtonMeters(3)); } [Fact] public void LengthDividedBySpeedEqualsDuration() { - Duration duration = Length.FromMeters(20) / Speed.FromMetersPerSecond(2); + var duration = Length.FromMeters(20) / Speed.FromMetersPerSecond(2); Assert.Equal(Duration.FromSeconds(10), duration); } [Fact] - public void LengthTimesSpeedEqualsKinematicViscosity() + public void LengthTimesAreaEqualsVolume() { - KinematicViscosity kinematicViscosity = Length.FromMeters(20) * Speed.FromMetersPerSecond(2); - Assert.Equal(KinematicViscosity.FromSquareMetersPerSecond(40), kinematicViscosity); + var volume = Length.FromMeters(3) * Area.FromSquareMeters(9); + Assert.Equal(volume, Volume.FromCubicMeters(27)); } [Fact] - public void LengthTimesSpecificWeightEqualsPressure() + public void LengthTimesForceEqualsTorque() { - Pressure pressure = Length.FromMeters(2) * SpecificWeight.FromNewtonsPerCubicMeter(10); - Assert.Equal(Pressure.FromPascals(20), pressure); + var torque = Length.FromMeters(3) * Force.FromNewtons(1); + Assert.Equal(torque, Torque.FromNewtonMeters(3)); } [Fact] - public void ToStringReturnsCorrectNumberAndUnitWithDefaultUnitWhichIsMeter() + public void LengthTimesLengthEqualsArea() { - var meter = Length.FromMeters(5); - string meterString = meter.ToString(); - Assert.Equal("5 m", meterString); + var area = Length.FromMeters(10) * Length.FromMeters(2); + Assert.Equal(area, Area.FromSquareMeters(20)); } [Fact] - public void ToStringReturnsCorrectNumberAndUnitWithCentimeterAsDefualtUnit() + public void LengthTimesSpecificWeightEqualsPressure() { - var value = Length.From(2, LengthUnit.Centimeter); - string valueString = value.ToString(); - Assert.Equal("2 cm", valueString); + var pressure = Length.FromMeters(2) * SpecificWeight.FromNewtonsPerCubicMeter(10); + Assert.Equal(Pressure.FromPascals(20), pressure); + } + + [Fact] + public void LengthTimesSpeedEqualsKinematicViscosity() + { + var kinematicViscosity = Length.FromMeters(20) * Speed.FromMetersPerSecond(2); + Assert.Equal(KinematicViscosity.FromSquareMetersPerSecond(40), kinematicViscosity); } [Fact] @@ -174,30 +185,19 @@ public void NegativeLengthToStonePoundsReturnsCorrectValues() } [Fact] - public void Constructor_UnitSystemNull_ThrowsArgumentNullException() - { - Assert.Throws(() => new Length(1.0, (UnitSystem)null)); - } - - [Fact] - public void Constructor_UnitSystemSI_AssignsSIUnit() - { - var length = new Length(1.0, UnitSystem.SI); - Assert.Equal(LengthUnit.Meter, length.Unit); - } - - [Fact] - public void Constructor_UnitSystemWithNoMatchingBaseUnits_ThrowsArgumentException() + public void ToStringReturnsCorrectNumberAndUnitWithCentimeterAsDefualtUnit() { - // AmplitudeRatio is unitless. Can't have any matches :) - Assert.Throws(() => new AmplitudeRatio(1.0, UnitSystem.SI)); + var value = Length.From(2, LengthUnit.Centimeter); + var valueString = value.ToString(); + Assert.Equal("2 cm", valueString); } [Fact] - public void As_GivenSIUnitSystem_ReturnsSIValue() + public void ToStringReturnsCorrectNumberAndUnitWithDefaultUnitWhichIsMeter() { - var inches = new Length(2.0, LengthUnit.Inch); - Assert.Equal(0.0508, inches.As(UnitSystem.SI)); + var meter = Length.FromMeters(5); + var meterString = meter.ToString(); + Assert.Equal("5 m", meterString); } [Fact] diff --git a/UnitsNet.Tests/CustomCode/LevelTests.cs b/UnitsNet.Tests/CustomCode/LevelTests.cs index e5d81b2eb8..7a46941166 100644 --- a/UnitsNet.Tests/CustomCode/LevelTests.cs +++ b/UnitsNet.Tests/CustomCode/LevelTests.cs @@ -14,13 +14,13 @@ public class LevelTests : LevelTestsBase protected override void AssertLogarithmicAddition() { - Level v = Level.FromDecibels(40); + var v = Level.FromDecibels(40); AssertEx.EqualTolerance(43.0102999566, (v + v).Decibels, DecibelsTolerance); } protected override void AssertLogarithmicSubtraction() { - Level v = Level.FromDecibels(40); + var v = Level.FromDecibels(40); AssertEx.EqualTolerance(49.5424250944, (Level.FromDecibels(50) - v).Decibels, DecibelsTolerance); } diff --git a/UnitsNet.Tests/CustomCode/MassFlowTests.cs b/UnitsNet.Tests/CustomCode/MassFlowTests.cs index b407d74dfa..2e64d25c0f 100644 --- a/UnitsNet.Tests/CustomCode/MassFlowTests.cs +++ b/UnitsNet.Tests/CustomCode/MassFlowTests.cs @@ -79,78 +79,78 @@ public class MassFlowTests : MassFlowTestsBase [Fact] public void DurationTimesMassFlowEqualsMass() { - Mass mass = Duration.FromSeconds(4.0) * MassFlow.FromKilogramsPerSecond(20.0); + var mass = Duration.FromSeconds(4.0) * MassFlow.FromKilogramsPerSecond(20.0); Assert.Equal(mass, Mass.FromKilograms(80.0)); } [Fact] - public void MassFlowTimesDurationEqualsMass() + public void MassFlowDividedByAreaEqualsMassFlux() { - Mass mass = MassFlow.FromKilogramsPerSecond(20.0) * Duration.FromSeconds(4.0); - Assert.Equal(mass, Mass.FromKilograms(80.0)); + var massFlux = MassFlow.FromKilogramsPerSecond(20) / Area.FromSquareMeters(2); + Assert.Equal(10, massFlux.KilogramsPerSecondPerSquareMeter); } [Fact] - public void MassFlowTimesTimeSpanEqualsMass() + public void MassFlowDividedByBrakeSpecificFuelConsumptionEqualsPower() { - Mass mass = MassFlow.FromKilogramsPerSecond(20.0) * TimeSpan.FromSeconds(4.0); - Assert.Equal(mass, Mass.FromKilograms(80.0)); + var power = MassFlow.FromTonnesPerDay(20) / BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0); + Assert.Equal(20.0 / 24.0 * 1e6 / 180.0, power.Kilowatts); } [Fact] - public void TimeSpanTimesMassFlowEqualsMass() + public void MassFlowDividedByDensityEqualsVolumeFlow() { - Mass mass = TimeSpan.FromSeconds(4.0) * MassFlow.FromKilogramsPerSecond(20.0); - Assert.Equal(mass, Mass.FromKilograms(80.0)); + var volumeFlow = MassFlow.FromKilogramsPerSecond(20) / Density.FromKilogramsPerCubicMeter(4); + Assert.Equal(5, volumeFlow.CubicMetersPerSecond); } [Fact] - public void MassFlowDividedByBrakeSpecificFuelConsumptionEqualsPower() + public void MassFlowDividedByMassFluxEqualsArea() { - Power power = MassFlow.FromTonnesPerDay(20) / BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0); - Assert.Equal(20.0 / 24.0 * 1e6 / 180.0, power.Kilowatts); + var area = MassFlow.FromKilogramsPerSecond(20) / MassFlux.FromKilogramsPerSecondPerSquareMeter(2); + Assert.Equal(10, area.SquareMeters); } [Fact] public void MassFlowDividedByPowerEqualsBrakeSpecificFuelConsumption() { - BrakeSpecificFuelConsumption bsfc = MassFlow.FromTonnesPerDay(20) / Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0); + var bsfc = MassFlow.FromTonnesPerDay(20) / Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0); AssertEx.EqualTolerance(180.0, bsfc.GramsPerKiloWattHour, 1e-11); } [Fact] - public void MassFlowTimesSpecificEnergyEqualsPower() + public void MassFlowDividedByVolumeFlowEqualsDensity() { - Power power = MassFlow.FromKilogramsPerSecond(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); - Assert.Equal(200, power.Watts); + var density = MassFlow.FromKilogramsPerSecond(12) / VolumeFlow.FromCubicMetersPerSecond(3); + Assert.Equal(4, density.KilogramsPerCubicMeter); } [Fact] - public void MassFlowDividedByAreaEqualsMassFlux() + public void MassFlowTimesDurationEqualsMass() { - MassFlux massFlux = MassFlow.FromKilogramsPerSecond(20) / Area.FromSquareMeters(2); - Assert.Equal(10, massFlux.KilogramsPerSecondPerSquareMeter); + var mass = MassFlow.FromKilogramsPerSecond(20.0) * Duration.FromSeconds(4.0); + Assert.Equal(mass, Mass.FromKilograms(80.0)); } [Fact] - public void MassFlowDividedByMassFluxEqualsArea() + public void MassFlowTimesSpecificEnergyEqualsPower() { - Area area = MassFlow.FromKilogramsPerSecond(20) / MassFlux.FromKilogramsPerSecondPerSquareMeter(2); - Assert.Equal(10, area.SquareMeters); + var power = MassFlow.FromKilogramsPerSecond(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); + Assert.Equal(200, power.Watts); } [Fact] - public void MassFlowDividedByVolumeFlowEqualsDensity() + public void MassFlowTimesTimeSpanEqualsMass() { - Density density = MassFlow.FromKilogramsPerSecond(12) / VolumeFlow.FromCubicMetersPerSecond(3); - Assert.Equal(4, density.KilogramsPerCubicMeter); + var mass = MassFlow.FromKilogramsPerSecond(20.0) * TimeSpan.FromSeconds(4.0); + Assert.Equal(mass, Mass.FromKilograms(80.0)); } [Fact] - public void MassFlowDividedByDensityEqualsVolumeFlow() + public void TimeSpanTimesMassFlowEqualsMass() { - VolumeFlow volumeFlow = MassFlow.FromKilogramsPerSecond(20) / Density.FromKilogramsPerCubicMeter(4); - Assert.Equal(5, volumeFlow.CubicMetersPerSecond); + var mass = TimeSpan.FromSeconds(4.0) * MassFlow.FromKilogramsPerSecond(20.0); + Assert.Equal(mass, Mass.FromKilograms(80.0)); } } } diff --git a/UnitsNet.Tests/CustomCode/MassTests.cs b/UnitsNet.Tests/CustomCode/MassTests.cs index 18cb904f33..0c501f2519 100644 --- a/UnitsNet.Tests/CustomCode/MassTests.cs +++ b/UnitsNet.Tests/CustomCode/MassTests.cs @@ -61,40 +61,57 @@ public class MassTests : MassTestsBase protected override double SolarMassesInOneKilogram => 5.0264643347223100000000000E-31; + [Theory] + [InlineData(10, MassUnit.Gram, + KnownQuantities.MolarMassOfOxygen, MolarMassUnit.GramPerMole, + 0.625023438378939, AmountOfSubstanceUnit.Mole)] // 10 grams Of Oxygen contain 0.625023438378939 Moles + public void AmountOfSubstanceFromMassAndMolarMass( + double massValue, MassUnit massUnit, + double molarMassValue, MolarMassUnit molarMassUnit, + double expectedAmountOfSubstanceValue, AmountOfSubstanceUnit expectedAmountOfSubstanceUnit, double tolerence = 1e-5) + { + var mass = new Mass(massValue, massUnit); + var molarMass = new MolarMass(molarMassValue, molarMassUnit); + + var amountOfSubstance = mass / molarMass; + + AssertEx.EqualTolerance(expectedAmountOfSubstanceValue, amountOfSubstance.As(expectedAmountOfSubstanceUnit), tolerence); + } + //protected override double SolarMassesTolerance => 0.1; [Fact] public void AccelerationTimesMassEqualsForce() { - Force force = Acceleration.FromMetersPerSecondSquared(3)*Mass.FromKilograms(18); + var force = Acceleration.FromMetersPerSecondSquared(3) * Mass.FromKilograms(18); Assert.Equal(force, Force.FromNewtons(54)); } [Fact] public void MassDividedByDurationEqualsMassFlow() { - MassFlow massFlow = Mass.FromKilograms(18.0)/Duration.FromSeconds(6); + var massFlow = Mass.FromKilograms(18.0) / Duration.FromSeconds(6); Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(3.0)); } [Fact] public void MassDividedByTimeSpanEqualsMassFlow() { - MassFlow massFlow = Mass.FromKilograms(18.0)/TimeSpan.FromSeconds(6); + var massFlow = Mass.FromKilograms(18.0) / TimeSpan.FromSeconds(6); Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(3.0)); } [Fact] public void MassDividedByVolumeEqualsDensity() { - Density density = Mass.FromKilograms(18)/Volume.FromCubicMeters(3); + var density = Mass.FromKilograms(18) / Volume.FromCubicMeters(3); Assert.Equal(density, Density.FromKilogramsPerCubicMeter(6)); } [Fact] public void MassTimesAccelerationEqualsForce() { - Force force = Mass.FromKilograms(18)*Acceleration.FromMetersPerSecondSquared(3); + var force = Mass.FromKilograms(18) * Acceleration.FromMetersPerSecondSquared(3); Assert.Equal(force, Force.FromNewtons(54)); } @@ -113,22 +130,5 @@ public void NegativeMassToStonePoundsReturnsCorrectValues() Assert.Equal(-1.0, stonePounds.Stone); Assert.Equal(-11.0, stonePounds.Pounds); } - - [Theory] - [InlineData(10, MassUnit.Gram, - KnownQuantities.MolarMassOfOxygen, MolarMassUnit.GramPerMole, - 0.625023438378939, AmountOfSubstanceUnit.Mole)] // 10 grams Of Oxygen contain 0.625023438378939 Moles - public void AmountOfSubstanceFromMassAndMolarMass( - double massValue, MassUnit massUnit, - double molarMassValue, MolarMassUnit molarMassUnit, - double expectedAmountOfSubstanceValue, AmountOfSubstanceUnit expectedAmountOfSubstanceUnit, double tolerence = 1e-5) - { - var mass = new Mass(massValue, massUnit); - var molarMass = new MolarMass(molarMassValue, molarMassUnit); - - AmountOfSubstance amountOfSubstance = mass / molarMass; - - AssertEx.EqualTolerance(expectedAmountOfSubstanceValue, amountOfSubstance.As(expectedAmountOfSubstanceUnit), tolerence); - } } } diff --git a/UnitsNet.Tests/CustomCode/ParseTests.cs b/UnitsNet.Tests/CustomCode/ParseTests.cs index 06a1f7cdc9..29f18928f3 100644 --- a/UnitsNet.Tests/CustomCode/ParseTests.cs +++ b/UnitsNet.Tests/CustomCode/ParseTests.cs @@ -27,8 +27,8 @@ public class ParseTests [InlineData("500,005 m", 500005)] public void ParseLengthToMetersUsEnglish(string s, double expected) { - CultureInfo usEnglish = new CultureInfo("en-US"); - double actual = Length.Parse(s, usEnglish).Meters; + var usEnglish = new CultureInfo("en-US"); + var actual = Length.Parse(s, usEnglish).Meters; Assert.Equal(expected, actual); } @@ -58,7 +58,7 @@ public void ParseWithCultureUsingSpaceAsThousandSeparators(string s, double expe numberFormat.NumberDecimalSeparator = "."; numberFormat.CurrencyDecimalSeparator = "."; - double actual = Length.Parse(s, numberFormat).Meters; + var actual = Length.Parse(s, numberFormat).Meters; Assert.Equal(expected, actual); } @@ -89,17 +89,10 @@ public void ParseWithCultureUsingDotAsThousandSeparators(string s, double expect numberFormat.NumberDecimalSeparator = ","; numberFormat.CurrencyDecimalSeparator = ","; - double actual = Length.Parse(s, numberFormat).Meters; + var actual = Length.Parse(s, numberFormat).Meters; Assert.Equal(expected, actual); } - [Fact] - public void ParseMultiWordAbbreviations() - { - Assert.Equal(Mass.FromShortTons(333), Mass.Parse("333 short tn")); - Assert.Equal(Mass.FromLongTons(333), Mass.Parse("333 long tn")); - } - [Theory] [InlineData("500 005 m", typeof(FormatException))] // Quantity doesn't match number format. public void ParseWithCultureUsingDotAsThousandSeparators_ThrowsExceptionOnInvalidString(string s, Type expectedExceptionType) @@ -117,8 +110,8 @@ public void ParseWithCultureUsingDotAsThousandSeparators_ThrowsExceptionOnInvali [InlineData("m", LengthUnit.Meter)] public void ParseLengthUnitUsEnglish(string s, LengthUnit expected) { - CultureInfo usEnglish = new CultureInfo("en-US"); - LengthUnit actual = Length.ParseUnit(s, usEnglish); + var usEnglish = new CultureInfo("en-US"); + var actual = Length.ParseUnit(s, usEnglish); Assert.Equal(expected, actual); } @@ -139,8 +132,8 @@ public void ParseLengthUnitUsEnglish_ThrowsExceptionOnInvalidString(string s, Ty [InlineData("foo", false)] public void TryParseLengthUnitUsEnglish(string s, bool expected) { - CultureInfo usEnglish = new CultureInfo("en-US"); - bool actual = Length.TryParse(s, usEnglish, out Length _); + var usEnglish = new CultureInfo("en-US"); + var actual = Length.TryParse(s, usEnglish, out _); Assert.Equal(expected, actual); } @@ -151,7 +144,8 @@ public void TryParseLengthUnitUsEnglish(string s, bool expected) [InlineData("1 г", "ru-RU", 1, MassUnit.Gram)] [InlineData("1 kg", "en-US", 1, MassUnit.Kilogram)] [InlineData("1 кг", "ru-RU", 1, MassUnit.Kilogram)] - public void ParseMassWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, Enum expectedUnit) + public void ParseMassWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, + Enum expectedUnit) { var actual = Mass.Parse(str, new CultureInfo(cultureName)); @@ -166,7 +160,8 @@ public void ParseMassWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAnd [InlineData("1 м", "ru-RU", 1, LengthUnit.Meter)] [InlineData("1 km", "en-US", 1, LengthUnit.Kilometer)] [InlineData("1 км", "ru-RU", 1, LengthUnit.Kilometer)] - public void ParseLengthWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, Enum expectedUnit) + public void ParseLengthWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, + Enum expectedUnit) { var actual = Length.Parse(str, new CultureInfo(cultureName)); @@ -181,7 +176,8 @@ public void ParseLengthWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitA [InlineData("1 Н", "ru-RU", 1, ForceUnit.Newton)] [InlineData("1 kN", "en-US", 1, ForceUnit.Kilonewton)] [InlineData("1 кН", "ru-RU", 1, ForceUnit.Kilonewton)] - public void ParseForceWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, Enum expectedUnit) + public void ParseForceWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, + Enum expectedUnit) { var actual = Force.Parse(str, new CultureInfo(cultureName)); @@ -202,12 +198,20 @@ public void ParseForceWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAn [InlineData("1 MB", "ru-RU", 1, InformationUnit.Megabyte)] [InlineData("1 MiB", "en-US", 1, InformationUnit.Mebibyte)] [InlineData("1 MiB", "ru-RU", 1, InformationUnit.Mebibyte)] - public void ParseInformationWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, decimal expectedValue, Enum expectedUnit) + public void ParseInformationWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, decimal expectedValue, + Enum expectedUnit) { var actual = Information.Parse(str, new CultureInfo(cultureName)); Assert.Equal(expectedUnit, actual.Unit); Assert.Equal(expectedValue, actual.Value); } + + [Fact] + public void ParseMultiWordAbbreviations() + { + Assert.Equal(Mass.FromShortTons(333), Mass.Parse("333 short tn")); + Assert.Equal(Mass.FromLongTons(333), Mass.Parse("333 long tn")); + } } } diff --git a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs index 896c60b9bc..5e8e287a1e 100644 --- a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs @@ -14,13 +14,13 @@ public class PowerRatioTests : PowerRatioTestsBase protected override void AssertLogarithmicAddition() { - PowerRatio v = PowerRatio.FromDecibelWatts(40); + var v = PowerRatio.FromDecibelWatts(40); AssertEx.EqualTolerance(43.0102999566, (v + v).DecibelWatts, DecibelWattsTolerance); } protected override void AssertLogarithmicSubtraction() { - PowerRatio v = PowerRatio.FromDecibelWatts(40); + var v = PowerRatio.FromDecibelWatts(40); AssertEx.EqualTolerance(49.5424250944, (PowerRatio.FromDecibelWatts(50) - v).DecibelWatts, DecibelWattsTolerance); } @@ -39,8 +39,8 @@ public void InvalidPower_ExpectArgumentOutOfRangeException(double power) [InlineData(100, 20)] public void ExpectPowerConvertedCorrectly(double power, double expected) { - Power p = Power.FromWatts(power); - double actual = PowerRatio.FromPower(p).DecibelWatts; + var p = Power.FromWatts(power); + var actual = PowerRatio.FromPower(p).DecibelWatts; Assert.Equal(expected, actual); } @@ -52,8 +52,8 @@ public void ExpectPowerConvertedCorrectly(double power, double expected) [InlineData(20, 100)] public void ExpectPowerRatioConvertedCorrectly(double powerRatio, double expected) { - PowerRatio pr = PowerRatio.FromDecibelWatts(powerRatio); - double actual = pr.ToPower().Watts; + var pr = PowerRatio.FromDecibelWatts(powerRatio); + var actual = pr.ToPower().Watts; Assert.Equal(expected, actual); } @@ -66,9 +66,9 @@ public void ExpectPowerRatioConvertedCorrectly(double powerRatio, double expecte [InlineData(-6.99, 40)] public void PowerRatioToAmplitudeRatio_50OhmImpedance(double dBmW, double expected) { - PowerRatio powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); + var powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); - double actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(50)).DecibelMillivolts, 2); + var actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(50)).DecibelMillivolts, 2); Assert.Equal(expected, actual); } @@ -79,9 +79,9 @@ public void PowerRatioToAmplitudeRatio_50OhmImpedance(double dBmW, double expect [InlineData(-8.75, 40)] public void PowerRatioToAmplitudeRatio_75OhmImpedance(double dBmW, double expected) { - PowerRatio powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); + var powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); - double actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(75)).DecibelMillivolts, 2); + var actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(75)).DecibelMillivolts, 2); Assert.Equal(expected, actual); } } diff --git a/UnitsNet.Tests/CustomCode/PowerTests.cs b/UnitsNet.Tests/CustomCode/PowerTests.cs index 45821fdb81..bd6f6a18ad 100644 --- a/UnitsNet.Tests/CustomCode/PowerTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerTests.cs @@ -61,71 +61,71 @@ public class PowerTests : PowerTestsBase [Fact] public void DurationTimesPowerEqualsEnergy() { - Energy energy = Duration.FromSeconds(8.0) * Power.FromWatts(5.0); + var energy = Duration.FromSeconds(8.0) * Power.FromWatts(5.0); Assert.Equal(energy, Energy.FromJoules(40.0)); } [Fact] - public void PowerDividedByRotationalSpeedEqualsForce() + public void PowerDividedByMassFlowEqualsSpecificEnergy() { - Torque torque = Power.FromWatts(15.0) / RotationalSpeed.FromRadiansPerSecond(3); - Assert.Equal(torque, Torque.FromNewtonMeters(5)); + var specificEnergy = Power.FromWatts(15.0) / MassFlow.FromKilogramsPerSecond(3); + Assert.Equal(specificEnergy, SpecificEnergy.FromJoulesPerKilogram(5)); } [Fact] - public void PowerDividedBySpeedEqualsForce() + public void PowerDividedByRotationalSpeedEqualsForce() { - Force force = Power.FromWatts(15.0) / Speed.FromMetersPerSecond(3); - Assert.Equal(force, Force.FromNewtons(5)); + var torque = Power.FromWatts(15.0) / RotationalSpeed.FromRadiansPerSecond(3); + Assert.Equal(torque, Torque.FromNewtonMeters(5)); } [Fact] - public void PowerDividedByTorqueEqualsRotationalSpeed() + public void PowerDividedBySpecificEnergyEqualsMassFlow() { - RotationalSpeed rotationalSpeed = Power.FromWatts(15.0) / Torque.FromNewtonMeters(3); - Assert.Equal(rotationalSpeed, RotationalSpeed.FromRadiansPerSecond(5)); + var massFlow = Power.FromWatts(15.0) / SpecificEnergy.FromJoulesPerKilogram(3); + Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(5)); } [Fact] - public void PowerTimesDurationEqualsEnergy() + public void PowerDividedBySpeedEqualsForce() { - Energy energy = Power.FromWatts(5.0) * Duration.FromSeconds(8.0); - Assert.Equal(energy, Energy.FromJoules(40.0)); + var force = Power.FromWatts(15.0) / Speed.FromMetersPerSecond(3); + Assert.Equal(force, Force.FromNewtons(5)); } [Fact] - public void PowerTimesTimeSpanEqualsEnergy() + public void PowerDividedByTorqueEqualsRotationalSpeed() { - Energy energy = Power.FromWatts(5.0) * TimeSpan.FromSeconds(8.0); - Assert.Equal(energy, Energy.FromJoules(40.0)); + var rotationalSpeed = Power.FromWatts(15.0) / Torque.FromNewtonMeters(3); + Assert.Equal(rotationalSpeed, RotationalSpeed.FromRadiansPerSecond(5)); } [Fact] - public void TimeSpanTimesPowerEqualsEnergy() + public void PowerTimesBrakeSpecificFuelConsumptionEqualsMassFlow() { - Energy energy = TimeSpan.FromSeconds(8.0) * Power.FromWatts(5.0); - Assert.Equal(energy, Energy.FromJoules(40.0)); + var massFlow = Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0) * BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0); + AssertEx.EqualTolerance(massFlow.TonnesPerDay, 20.0, 1e-11); } [Fact] - public void PowerTimesBrakeSpecificFuelConsumptionEqualsMassFlow() + public void PowerTimesDurationEqualsEnergy() { - MassFlow massFlow = Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0) * BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0); - AssertEx.EqualTolerance(massFlow.TonnesPerDay, 20.0, 1e-11); + var energy = Power.FromWatts(5.0) * Duration.FromSeconds(8.0); + Assert.Equal(energy, Energy.FromJoules(40.0)); } [Fact] - public void PowerDividedByMassFlowEqualsSpecificEnergy() + public void PowerTimesTimeSpanEqualsEnergy() { - SpecificEnergy specificEnergy = Power.FromWatts(15.0) / MassFlow.FromKilogramsPerSecond(3); - Assert.Equal(specificEnergy, SpecificEnergy.FromJoulesPerKilogram(5)); + var energy = Power.FromWatts(5.0) * TimeSpan.FromSeconds(8.0); + Assert.Equal(energy, Energy.FromJoules(40.0)); } [Fact] - public void PowerDividedBySpecificEnergyEqualsMassFlow() + public void TimeSpanTimesPowerEqualsEnergy() { - MassFlow massFlow = Power.FromWatts(15.0) / SpecificEnergy.FromJoulesPerKilogram(3); - Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(5)); + var energy = TimeSpan.FromSeconds(8.0) * Power.FromWatts(5.0); + Assert.Equal(energy, Energy.FromJoules(40.0)); } } } diff --git a/UnitsNet.Tests/CustomCode/PressureChangeRateTests.cs b/UnitsNet.Tests/CustomCode/PressureChangeRateTests.cs index fe16b06d88..e0d6baf1e3 100644 --- a/UnitsNet.Tests/CustomCode/PressureChangeRateTests.cs +++ b/UnitsNet.Tests/CustomCode/PressureChangeRateTests.cs @@ -5,7 +5,7 @@ namespace UnitsNet.Tests.CustomCode { public class PressureChangeRateTests : PressureChangeRateTestsBase { - protected override double AtmospheresPerSecondInOnePascalPerSecond => 9.8692*1E-6; + protected override double AtmospheresPerSecondInOnePascalPerSecond => 9.8692 * 1E-6; protected override double KilopascalsPerSecondInOnePascalPerSecond => 1e-3; diff --git a/UnitsNet.Tests/CustomCode/RotationalSpeedTests.cs b/UnitsNet.Tests/CustomCode/RotationalSpeedTests.cs index e65f9f8f92..93db5f818a 100644 --- a/UnitsNet.Tests/CustomCode/RotationalSpeedTests.cs +++ b/UnitsNet.Tests/CustomCode/RotationalSpeedTests.cs @@ -37,28 +37,28 @@ public class RotationalSpeedTests : RotationalSpeedTestsBase [Fact] public void DurationTimesRotationalSpeedEqualsAngle() { - Angle angle = Duration.FromSeconds(9.0)*RotationalSpeed.FromRadiansPerSecond(10.0); + var angle = Duration.FromSeconds(9.0) * RotationalSpeed.FromRadiansPerSecond(10.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } [Fact] public void RotationalSpeedTimesDurationEqualsAngle() { - Angle angle = RotationalSpeed.FromRadiansPerSecond(10.0)*Duration.FromSeconds(9.0); + var angle = RotationalSpeed.FromRadiansPerSecond(10.0) * Duration.FromSeconds(9.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } [Fact] public void RotationalSpeedTimesTimeSpanEqualsAngle() { - Angle angle = RotationalSpeed.FromRadiansPerSecond(10.0)*TimeSpan.FromSeconds(9.0); + var angle = RotationalSpeed.FromRadiansPerSecond(10.0) * TimeSpan.FromSeconds(9.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } [Fact] public void TimeSpanTimesRotationalSpeedEqualsAngle() { - Angle angle = TimeSpan.FromSeconds(9.0)*RotationalSpeed.FromRadiansPerSecond(10.0); + var angle = TimeSpan.FromSeconds(9.0) * RotationalSpeed.FromRadiansPerSecond(10.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } } diff --git a/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs b/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs index ce4904b089..d1af883fd5 100644 --- a/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs +++ b/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs @@ -18,38 +18,38 @@ public class SpecificEnergyTests : SpecificEnergyTestsBase protected override double MegawattHoursPerKilogramInOneJoulePerKilogram => 2.77777778e-10; [Fact] - public void MassTimesSpecificEnergyEqualsEnergy() + public void DoubleDividedBySpecificEnergyEqualsBrakeSpecificFuelConsumption() { - Energy energy = Mass.FromKilograms(20.0)*SpecificEnergy.FromJoulesPerKilogram(10.0); - Assert.Equal(200d, energy.Joules); + var bsfc = 2.0 / SpecificEnergy.FromJoulesPerKilogram(4.0); + Assert.Equal(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(0.5), bsfc); } [Fact] - public void SpecificEnergyTimesMassEqualsEnergy() + public void MassTimesSpecificEnergyEqualsEnergy() { - Energy energy = SpecificEnergy.FromJoulesPerKilogram(10.0)*Mass.FromKilograms(20.0); + var energy = Mass.FromKilograms(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); Assert.Equal(200d, energy.Joules); } [Fact] - public void DoubleDividedBySpecificEnergyEqualsBrakeSpecificFuelConsumption() + public void SpecificEnergyTimesBrakeSpecificFuelConsumptionEqualsEnergy() { - BrakeSpecificFuelConsumption bsfc = 2.0 / SpecificEnergy.FromJoulesPerKilogram(4.0); - Assert.Equal(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(0.5), bsfc); + var value = SpecificEnergy.FromJoulesPerKilogram(10.0) * BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0); + Assert.Equal(200d, value); } [Fact] - public void SpecificEnergyTimesMassFlowEqualsPower() + public void SpecificEnergyTimesMassEqualsEnergy() { - Power power = SpecificEnergy.FromJoulesPerKilogram(10.0) * MassFlow.FromKilogramsPerSecond(20.0); - Assert.Equal(200d, power.Watts); + var energy = SpecificEnergy.FromJoulesPerKilogram(10.0) * Mass.FromKilograms(20.0); + Assert.Equal(200d, energy.Joules); } [Fact] - public void SpecificEnergyTimesBrakeSpecificFuelConsumptionEqualsEnergy() + public void SpecificEnergyTimesMassFlowEqualsPower() { - double value = SpecificEnergy.FromJoulesPerKilogram(10.0) * BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0); - Assert.Equal(200d, value); + var power = SpecificEnergy.FromJoulesPerKilogram(10.0) * MassFlow.FromKilogramsPerSecond(20.0); + Assert.Equal(200d, power.Watts); } } } diff --git a/UnitsNet.Tests/CustomCode/SpecificWeightTests.cs b/UnitsNet.Tests/CustomCode/SpecificWeightTests.cs index ca86cd7f5e..541ca69b25 100644 --- a/UnitsNet.Tests/CustomCode/SpecificWeightTests.cs +++ b/UnitsNet.Tests/CustomCode/SpecificWeightTests.cs @@ -42,24 +42,24 @@ public class SpecificWeightTests : SpecificWeightTestsBase protected override double MeganewtonsPerCubicMeterInOneNewtonPerCubicMeter => 1e-6; [Fact] - public void SpecificWeightTimesLengthEqualsPressure() + public void SpecificWeightDividedByAccelerationEqualsDensity() { - Pressure pressure = SpecificWeight.FromNewtonsPerCubicMeter(10) * Length.FromMeters(2); - Assert.Equal(Pressure.FromPascals(20), pressure); + var density = SpecificWeight.FromNewtonsPerCubicMeter(20) / Acceleration.FromMetersPerSecondSquared(2); + Assert.Equal(Density.FromKilogramsPerCubicMeter(10), density); } [Fact] public void SpecificWeightDividedByDensityEqualsAcceleration() { - Acceleration acceleration = SpecificWeight.FromNewtonsPerCubicMeter(40) / Density.FromKilogramsPerCubicMeter(4); + var acceleration = SpecificWeight.FromNewtonsPerCubicMeter(40) / Density.FromKilogramsPerCubicMeter(4); Assert.Equal(Acceleration.FromMetersPerSecondSquared(10), acceleration); } [Fact] - public void SpecificWeightDividedByAccelerationEqualsDensity() + public void SpecificWeightTimesLengthEqualsPressure() { - Density density = SpecificWeight.FromNewtonsPerCubicMeter(20) / Acceleration.FromMetersPerSecondSquared(2); - Assert.Equal(Density.FromKilogramsPerCubicMeter(10), density); + var pressure = SpecificWeight.FromNewtonsPerCubicMeter(10) * Length.FromMeters(2); + Assert.Equal(Pressure.FromPascals(20), pressure); } } } diff --git a/UnitsNet.Tests/CustomCode/SpeedTests.cs b/UnitsNet.Tests/CustomCode/SpeedTests.cs index cc96ce9c80..98dd17bde7 100644 --- a/UnitsNet.Tests/CustomCode/SpeedTests.cs +++ b/UnitsNet.Tests/CustomCode/SpeedTests.cs @@ -75,63 +75,63 @@ public class SpeedTests : SpeedTestsBase [Fact] public void DurationSpeedTimesEqualsLength() { - Length length = Duration.FromSeconds(2)*Speed.FromMetersPerSecond(20); + var length = Duration.FromSeconds(2) * Speed.FromMetersPerSecond(20); Assert.Equal(length, Length.FromMeters(40)); } [Fact] public void LengthDividedByDurationEqualsSpeed() { - Speed speed = Length.FromMeters(20)/Duration.FromSeconds(2); + var speed = Length.FromMeters(20) / Duration.FromSeconds(2); Assert.Equal(speed, Speed.FromMetersPerSecond(10)); } [Fact] public void LengthDividedByTimeSpanEqualsSpeed() { - Speed speed = Length.FromMeters(20)/TimeSpan.FromSeconds(2); + var speed = Length.FromMeters(20) / TimeSpan.FromSeconds(2); Assert.Equal(speed, Speed.FromMetersPerSecond(10)); } [Fact] public void SpeedDividedByDurationEqualsAcceleration() { - Acceleration acceleration = Speed.FromMetersPerSecond(20)/Duration.FromSeconds(2); + var acceleration = Speed.FromMetersPerSecond(20) / Duration.FromSeconds(2); Assert.Equal(acceleration, Acceleration.FromMetersPerSecondSquared(10)); } [Fact] public void SpeedDividedByTimeSpanEqualsAcceleration() { - Acceleration acceleration = Speed.FromMetersPerSecond(20)/TimeSpan.FromSeconds(2); + var acceleration = Speed.FromMetersPerSecond(20) / TimeSpan.FromSeconds(2); Assert.Equal(acceleration, Acceleration.FromMetersPerSecondSquared(10)); } [Fact] - public void SpeedTimesDurationEqualsLength() + public void SpeedTimesAreaEqualsVolumeFlow() { - Length length = Speed.FromMetersPerSecond(20)*Duration.FromSeconds(2); - Assert.Equal(length, Length.FromMeters(40)); + var volumeFlow = Speed.FromMetersPerSecond(2) * Area.FromSquareMeters(20); + Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(40), volumeFlow); } [Fact] - public void SpeedTimesTimeSpanEqualsLength() + public void SpeedTimesDensityEqualsMassFlux() { - Length length = Speed.FromMetersPerSecond(20)*TimeSpan.FromSeconds(2); - Assert.Equal(length, Length.FromMeters(40)); + var massFlux = Speed.FromMetersPerSecond(20) * Density.FromKilogramsPerCubicMeter(2); + Assert.Equal(massFlux, MassFlux.FromKilogramsPerSecondPerSquareMeter(40)); } [Fact] - public void TimeSpanTimesSpeedEqualsLength() + public void SpeedTimesDurationEqualsLength() { - Length length = TimeSpan.FromSeconds(2)*Speed.FromMetersPerSecond(20); + var length = Speed.FromMetersPerSecond(20) * Duration.FromSeconds(2); Assert.Equal(length, Length.FromMeters(40)); } [Fact] public void SpeedTimesLengthEqualsKinematicViscosity() { - KinematicViscosity kinematicViscosity = Length.FromMeters(20) * Speed.FromMetersPerSecond(2); + var kinematicViscosity = Length.FromMeters(20) * Speed.FromMetersPerSecond(2); Assert.Equal(KinematicViscosity.FromSquareMetersPerSecond(40), kinematicViscosity); } @@ -139,22 +139,22 @@ public void SpeedTimesLengthEqualsKinematicViscosity() public void SpeedTimesSpeedEqualsSpecificEnergy() { //m^2/s^2 = kg*m*m/(s^2*kg) = J/kg - SpecificEnergy length = Speed.FromMetersPerSecond(2) * Speed.FromMetersPerSecond(20); + var length = Speed.FromMetersPerSecond(2) * Speed.FromMetersPerSecond(20); Assert.Equal(length, SpecificEnergy.FromJoulesPerKilogram(40)); } [Fact] - public void SpeedTimesDensityEqualsMassFlux() + public void SpeedTimesTimeSpanEqualsLength() { - MassFlux massFlux = Speed.FromMetersPerSecond(20) * Density.FromKilogramsPerCubicMeter(2); - Assert.Equal(massFlux, MassFlux.FromKilogramsPerSecondPerSquareMeter(40)); + var length = Speed.FromMetersPerSecond(20) * TimeSpan.FromSeconds(2); + Assert.Equal(length, Length.FromMeters(40)); } [Fact] - public void SpeedTimesAreaEqualsVolumeFlow() + public void TimeSpanTimesSpeedEqualsLength() { - VolumeFlow volumeFlow = Speed.FromMetersPerSecond(2) * Area.FromSquareMeters(20); - Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(40), volumeFlow); + var length = TimeSpan.FromSeconds(2) * Speed.FromMetersPerSecond(20); + Assert.Equal(length, Length.FromMeters(40)); } } } diff --git a/UnitsNet.Tests/CustomCode/StonePoundsTests.cs b/UnitsNet.Tests/CustomCode/StonePoundsTests.cs index b8cafbb920..2b1bafc13d 100644 --- a/UnitsNet.Tests/CustomCode/StonePoundsTests.cs +++ b/UnitsNet.Tests/CustomCode/StonePoundsTests.cs @@ -13,19 +13,32 @@ public class StonePoundsTests private const double StoneTolerance = 1e-4; private const double PoundsTolerance = 1e-4; + // These cultures use a thin space in digit grouping + [Theory] + [InlineData("nn-NO")] + [InlineData("fr-FR")] + public void StonePoundsToString_GivenCultureWithThinSpaceDigitGroup_ReturnsNumberWithThinSpaceDigitGroup(string cultureName) + { + var formatProvider = new CultureInfo(cultureName); + var m = Mass.FromStonePounds(3500, 1); + var stonePounds = m.StonePounds; + + Assert.Equal("3 500 st 1 lb", stonePounds.ToString(formatProvider)); + } + [Fact] public void StonePoundsFrom() { - Mass m = Mass.FromStonePounds(2, 3); - double expectedKg = 2/StoneInOneKilogram + 3/PoundsInOneKilogram; + var m = Mass.FromStonePounds(2, 3); + var expectedKg = 2 / StoneInOneKilogram + 3 / PoundsInOneKilogram; AssertEx.EqualTolerance(expectedKg, m.Kilograms, StoneTolerance); } [Fact] public void StonePoundsRoundTrip() { - Mass m = Mass.FromStonePounds(2, 3); - StonePounds stonePounds = m.StonePounds; + var m = Mass.FromStonePounds(2, 3); + var stonePounds = m.StonePounds; AssertEx.EqualTolerance(2, stonePounds.Stone, StoneTolerance); AssertEx.EqualTolerance(3, stonePounds.Pounds, PoundsTolerance); } @@ -33,24 +46,11 @@ public void StonePoundsRoundTrip() [Fact] public void StonePoundsToString_FormatsNumberInDefaultCulture() { - Mass m = Mass.FromStonePounds(3500, 1); - StonePounds stonePounds = m.StonePounds; - string numberInCurrentCulture = 3500.ToString("n0", CultureInfo.CurrentUICulture); // Varies between machines, can't hard code it + var m = Mass.FromStonePounds(3500, 1); + var stonePounds = m.StonePounds; + var numberInCurrentCulture = 3500.ToString("n0", CultureInfo.CurrentUICulture); // Varies between machines, can't hard code it Assert.Equal($"{numberInCurrentCulture} st 1 lb", stonePounds.ToString()); } - - // These cultures use a thin space in digit grouping - [Theory] - [InlineData("nn-NO")] - [InlineData("fr-FR")] - public void StonePoundsToString_GivenCultureWithThinSpaceDigitGroup_ReturnsNumberWithThinSpaceDigitGroup(string cultureName) - { - var formatProvider = new CultureInfo(cultureName); - Mass m = Mass.FromStonePounds(3500, 1); - StonePounds stonePounds = m.StonePounds; - - Assert.Equal("3 500 st 1 lb", stonePounds.ToString(formatProvider)); - } } } diff --git a/UnitsNet.Tests/CustomCode/TemperatureChangeRateTests.cs b/UnitsNet.Tests/CustomCode/TemperatureChangeRateTests.cs index 17f17a8201..f7f3938afa 100644 --- a/UnitsNet.Tests/CustomCode/TemperatureChangeRateTests.cs +++ b/UnitsNet.Tests/CustomCode/TemperatureChangeRateTests.cs @@ -23,6 +23,6 @@ public class TemperatureChangeRateTests : TemperatureChangeRateTestsBase protected override double NanodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond => 1E9; - protected override double DegreesCelsiusPerMinuteInOneDegreeCelsiusPerSecond => 60; + protected override double DegreesCelsiusPerMinuteInOneDegreeCelsiusPerSecond => 60; } } diff --git a/UnitsNet.Tests/CustomCode/TemperatureTests.cs b/UnitsNet.Tests/CustomCode/TemperatureTests.cs index 05b0cf511d..1a7285258b 100644 --- a/UnitsNet.Tests/CustomCode/TemperatureTests.cs +++ b/UnitsNet.Tests/CustomCode/TemperatureTests.cs @@ -30,12 +30,56 @@ public class TemperatureTests : TemperatureTestsBase public static IEnumerable DividedByTemperatureDeltaEqualsTemperatureData { get; } = new List { - new object[] { Temperature.FromDegreesCelsius(10), 1, Temperature.FromDegreesCelsius(10) }, - new object[] { Temperature.FromDegreesCelsius(10), 5, Temperature.FromDegreesCelsius(2) }, - new object[] { Temperature.FromDegreesCelsius(10), -10, Temperature.FromDegreesCelsius(-1) }, - new object[] { Temperature.FromDegreesFahrenheit(10), 1, Temperature.FromDegreesFahrenheit(10) }, - new object[] { Temperature.FromDegreesFahrenheit(10), 5, Temperature.FromDegreesFahrenheit(2) }, - new object[] { Temperature.FromDegreesFahrenheit(10), -10, Temperature.FromDegreesFahrenheit(-1) } + new object[] {Temperature.FromDegreesCelsius(10), 1, Temperature.FromDegreesCelsius(10)}, + new object[] {Temperature.FromDegreesCelsius(10), 5, Temperature.FromDegreesCelsius(2)}, + new object[] {Temperature.FromDegreesCelsius(10), -10, Temperature.FromDegreesCelsius(-1)}, + new object[] {Temperature.FromDegreesFahrenheit(10), 1, Temperature.FromDegreesFahrenheit(10)}, + new object[] {Temperature.FromDegreesFahrenheit(10), 5, Temperature.FromDegreesFahrenheit(2)}, + new object[] {Temperature.FromDegreesFahrenheit(10), -10, Temperature.FromDegreesFahrenheit(-1)} + }; + + public static IEnumerable MultiplyByTemperatureDeltaEqualsTemperatureData { get; } = + new List + { + new object[] {Temperature.FromDegreesCelsius(10), 0, Temperature.FromDegreesCelsius(0)}, + new object[] {Temperature.FromDegreesCelsius(10), 5, Temperature.FromDegreesCelsius(50)}, + new object[] {Temperature.FromDegreesCelsius(10), -5, Temperature.FromDegreesCelsius(-50)}, + new object[] {Temperature.FromDegreesFahrenheit(10), 0, Temperature.FromDegreesFahrenheit(0)}, + new object[] {Temperature.FromDegreesFahrenheit(10), 5, Temperature.FromDegreesFahrenheit(50)}, + new object[] {Temperature.FromDegreesFahrenheit(10), -5, Temperature.FromDegreesFahrenheit(-50)} + }; + + public static IEnumerable TemperatureDeltaPlusTemperatureEqualsTemperatureData { get; } = + new List + { + new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(0), Temperature.FromDegreesCelsius(-10)}, + new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(0)}, + new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(10)}, + new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(0), Temperature.FromDegreesFahrenheit(-10)}, + new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(0)}, + new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10)} + }; + + public static IEnumerable TemperatureMinusTemperatureDeltaEqualsTemperatureData { get; } = + new List + { + new object[] {Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(10)}, + new object[] {Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(0)}, + new object[] {Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(30), Temperature.FromDegreesCelsius(-10)}, + new object[] {Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(10)}, + new object[] {Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(0)}, + new object[] {Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(30), Temperature.FromDegreesFahrenheit(-10)} + }; + + public static IEnumerable TemperaturePlusTemperatureDeltaEqualsTemperatureData { get; } = + new List + { + new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(0), Temperature.FromDegreesCelsius(-10)}, + new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(0)}, + new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(10)}, + new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(0), Temperature.FromDegreesFahrenheit(-10)}, + new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(0)}, + new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10)} }; [SuppressMessage("ReSharper", "ImpureMethodCallOnReadonlyValueField", @@ -44,87 +88,42 @@ public class TemperatureTests : TemperatureTestsBase [MemberData(nameof(DividedByTemperatureDeltaEqualsTemperatureData))] public void DividedByTemperatureDeltaEqualsTemperature(Temperature temperature, int divisor, Temperature expected) { - Temperature resultTemp = temperature.Divide(divisor, temperature.Unit); + var resultTemp = temperature.Divide(divisor, temperature.Unit); Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); } - public static IEnumerable MultiplyByTemperatureDeltaEqualsTemperatureData { get; } = - new List - { - new object[] { Temperature.FromDegreesCelsius(10), 0, Temperature.FromDegreesCelsius(0) }, - new object[] { Temperature.FromDegreesCelsius(10), 5, Temperature.FromDegreesCelsius(50) }, - new object[] { Temperature.FromDegreesCelsius(10), -5, Temperature.FromDegreesCelsius(-50) }, - new object[] { Temperature.FromDegreesFahrenheit(10), 0, Temperature.FromDegreesFahrenheit(0) }, - new object[] { Temperature.FromDegreesFahrenheit(10), 5, Temperature.FromDegreesFahrenheit(50) }, - new object[] { Temperature.FromDegreesFahrenheit(10), -5, Temperature.FromDegreesFahrenheit(-50) } - }; - [SuppressMessage("ReSharper", "ImpureMethodCallOnReadonlyValueField", Justification = "R# incorrectly identifies method as impure, due to internal method calls.")] [Theory] [MemberData(nameof(MultiplyByTemperatureDeltaEqualsTemperatureData))] public void MultiplyByTemperatureDeltaEqualsTemperature(Temperature temperature, int factor, Temperature expected) { - Temperature resultTemp = temperature.Multiply(factor, temperature.Unit); + var resultTemp = temperature.Multiply(factor, temperature.Unit); Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); } - public static IEnumerable TemperatureDeltaPlusTemperatureEqualsTemperatureData { get; } = - new List - { - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(0), Temperature.FromDegreesCelsius(-10) }, - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(0) }, - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(10) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(0), Temperature.FromDegreesFahrenheit(-10) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(0) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10) } - }; - [Theory] [MemberData(nameof(TemperatureDeltaPlusTemperatureEqualsTemperatureData))] public void TemperatureDeltaPlusTemperatureEqualsTemperature(Temperature temperature, TemperatureDelta delta, Temperature expected) { - Temperature resultTemp = delta + temperature; + var resultTemp = delta + temperature; Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); } - public static IEnumerable TemperatureMinusTemperatureDeltaEqualsTemperatureData { get; } = - new List - { - new object[] { Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(10) }, - new object[] { Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(0) }, - new object[] { Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(30), Temperature.FromDegreesCelsius(-10) }, - new object[] { Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(10) }, - new object[] { Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(0) }, - new object[] { Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(30), Temperature.FromDegreesFahrenheit(-10) } - }; - [Theory] [MemberData(nameof(TemperatureMinusTemperatureDeltaEqualsTemperatureData))] public void TemperatureMinusTemperatureDeltaEqualsTemperature(Temperature temperature, TemperatureDelta delta, Temperature expected) { - Temperature resultTemp = temperature - delta; + var resultTemp = temperature - delta; Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); } - public static IEnumerable TemperaturePlusTemperatureDeltaEqualsTemperatureData { get; } = - new List - { - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(0), Temperature.FromDegreesCelsius(-10) }, - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(0) }, - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(10) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(0), Temperature.FromDegreesFahrenheit(-10) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(0) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10) } - }; - - [Theory] [MemberData(nameof(TemperaturePlusTemperatureDeltaEqualsTemperatureData))] public void TemperaturePlusTemperatureDeltaEqualsTemperature(Temperature temperature, TemperatureDelta delta, Temperature expected) { - Temperature resultTemp = temperature + delta; + var resultTemp = temperature + delta; Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); } } diff --git a/UnitsNet.Tests/CustomCode/TorqueTests.cs b/UnitsNet.Tests/CustomCode/TorqueTests.cs index aef7961cb1..a60df46868 100644 --- a/UnitsNet.Tests/CustomCode/TorqueTests.cs +++ b/UnitsNet.Tests/CustomCode/TorqueTests.cs @@ -52,14 +52,14 @@ public class TorqueTests : TorqueTestsBase [Fact] public void TorqueDividedByForceEqualsLength() { - Length length = Torque.FromNewtonMeters(4)/Force.FromNewtons(2); + var length = Torque.FromNewtonMeters(4) / Force.FromNewtons(2); Assert.Equal(length, Length.FromMeters(2)); } [Fact] public void TorqueDividedByLengthEqualsForce() { - Force force = Torque.FromNewtonMeters(4)/Length.FromMeters(2); + var force = Torque.FromNewtonMeters(4) / Length.FromMeters(2); Assert.Equal(force, Force.FromNewtons(2)); } } diff --git a/UnitsNet.Tests/CustomCode/VolumeTests.cs b/UnitsNet.Tests/CustomCode/VolumeTests.cs index ad6c2dca04..c459ecb911 100644 --- a/UnitsNet.Tests/CustomCode/VolumeTests.cs +++ b/UnitsNet.Tests/CustomCode/VolumeTests.cs @@ -94,48 +94,48 @@ public class VolumeTests : VolumeTestsBase protected override double ImperialPintsInOneCubicMeter => 1.7597539863927023e3; - [ Fact] - public void VolumeDividedByAreaEqualsLength() + [Theory] + [InlineData(20, 2, 10)] + [InlineData(20, 80, 0.25)] + public void VolumeDividedByTimeSpanEqualsVolumeFlow(double cubicMeters, double seconds, double expectedCubicMetersPerSecond) { - Length length = Volume.FromCubicMeters(15)/Area.FromSquareMeters(5); - Assert.Equal(length, Length.FromMeters(3)); + var volumeFlow = Volume.FromCubicMeters(cubicMeters) / TimeSpan.FromSeconds(seconds); + Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(expectedCubicMetersPerSecond), volumeFlow); } [Fact] - public void VolumeDividedByLengthEqualsArea() + public void VolumeDividedByAreaEqualsLength() { - Area area = Volume.FromCubicMeters(15)/Length.FromMeters(5); - Assert.Equal(area, Area.FromSquareMeters(3)); + var length = Volume.FromCubicMeters(15) / Area.FromSquareMeters(5); + Assert.Equal(length, Length.FromMeters(3)); } [Fact] - public void VolumeTimesDensityEqualsMass() + public void VolumeDividedByDurationEqualsVolumeFlow() { - Mass mass = Volume.FromCubicMeters(2)*Density.FromKilogramsPerCubicMeter(3); - Assert.Equal(mass, Mass.FromKilograms(6)); + var volumeFlow = Volume.FromCubicMeters(20) / Duration.FromSeconds(2); + Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(10), volumeFlow); } - [Theory] - [InlineData(20, 2, 10)] - [InlineData(20, 80, 0.25)] - public void VolumeDividedByTimeSpanEqualsVolumeFlow(double cubicMeters, double seconds, double expectedCubicMetersPerSecond) + [Fact] + public void VolumeDividedByLengthEqualsArea() { - VolumeFlow volumeFlow = Volume.FromCubicMeters(cubicMeters) / TimeSpan.FromSeconds(seconds); - Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(expectedCubicMetersPerSecond), volumeFlow); + var area = Volume.FromCubicMeters(15) / Length.FromMeters(5); + Assert.Equal(area, Area.FromSquareMeters(3)); } [Fact] - public void VolumeDividedByDurationEqualsVolumeFlow() + public void VolumeDividedByVolumeFlowEqualsTimeSpan() { - VolumeFlow volumeFlow = Volume.FromCubicMeters(20) / Duration.FromSeconds(2); - Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(10), volumeFlow); + var timeSpan = Volume.FromCubicMeters(20) / VolumeFlow.FromCubicMetersPerSecond(2); + Assert.Equal(TimeSpan.FromSeconds(10), timeSpan); } [Fact] - public void VolumeDividedByVolumeFlowEqualsTimeSpan() + public void VolumeTimesDensityEqualsMass() { - TimeSpan timeSpan = Volume.FromCubicMeters(20) / VolumeFlow.FromCubicMetersPerSecond(2); - Assert.Equal(TimeSpan.FromSeconds(10), timeSpan); + var mass = Volume.FromCubicMeters(2) * Density.FromKilogramsPerCubicMeter(3); + Assert.Equal(mass, Mass.FromKilograms(6)); } } } diff --git a/UnitsNet.Tests/CustomQuantities/HowMuch.cs b/UnitsNet.Tests/CustomQuantities/HowMuch.cs index 5f6bab3543..e7bc7a3d76 100644 --- a/UnitsNet.Tests/CustomQuantities/HowMuch.cs +++ b/UnitsNet.Tests/CustomQuantities/HowMuch.cs @@ -1,10 +1,13 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using System; namespace UnitsNet.Tests.CustomQuantities { - /// + /// /// - /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. + /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. /// public struct HowMuch : IQuantity { @@ -27,9 +30,8 @@ public HowMuch(double value, Enum unit) : this() public QuantityInfo QuantityInfo => new QuantityInfo(Type, new UnitInfo[] { - new UnitInfo(HowMuchUnit.Some, BaseUnits.Undefined), - new UnitInfo(HowMuchUnit.ATon, BaseUnits.Undefined), - new UnitInfo(HowMuchUnit.AShitTon, BaseUnits.Undefined), + new UnitInfo(HowMuchUnit.Some, BaseUnits.Undefined), new UnitInfo(HowMuchUnit.ATon, BaseUnits.Undefined), + new UnitInfo(HowMuchUnit.AShitTon, BaseUnits.Undefined) }, HowMuchUnit.Some, Zero, diff --git a/UnitsNet.Tests/CustomQuantities/HowMuchUnit.cs b/UnitsNet.Tests/CustomQuantities/HowMuchUnit.cs index c58f9fc548..a5aa6ee7c3 100644 --- a/UnitsNet.Tests/CustomQuantities/HowMuchUnit.cs +++ b/UnitsNet.Tests/CustomQuantities/HowMuchUnit.cs @@ -1,7 +1,10 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + namespace UnitsNet.Tests.CustomQuantities { /// - /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. + /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. /// public enum HowMuchUnit { diff --git a/UnitsNet.Tests/DecimalOverloadTests.cs b/UnitsNet.Tests/DecimalOverloadTests.cs index 841c9b162b..3740629a21 100644 --- a/UnitsNet.Tests/DecimalOverloadTests.cs +++ b/UnitsNet.Tests/DecimalOverloadTests.cs @@ -8,17 +8,17 @@ namespace UnitsNet.Tests public class DecimalOverloadTests { [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromDecimalReturnsCorrectValue() + public static void CreatingQuantityWithDecimalBackingFieldFromDecimalReturnsCorrectValue() { - Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(1m); - Assert.Equal(1.0, acceleration.MetersPerSecondSquared); + var power = Power.FromWatts(1m); + Assert.Equal(1.0, power.Watts); } [Fact] - public static void CreatingQuantityWithDecimalBackingFieldFromDecimalReturnsCorrectValue() + public static void CreatingQuantityWithDoubleBackingFieldFromDecimalReturnsCorrectValue() { - Power power = Power.FromWatts(1m); - Assert.Equal(1.0, power.Watts); + var acceleration = Acceleration.FromMetersPerSecondSquared(1m); + Assert.Equal(1.0, acceleration.MetersPerSecondSquared); } } } diff --git a/UnitsNet.Tests/DummyIQuantity.cs b/UnitsNet.Tests/DummyIQuantity.cs index 04f97a7ea2..52a6de8d0f 100644 --- a/UnitsNet.Tests/DummyIQuantity.cs +++ b/UnitsNet.Tests/DummyIQuantity.cs @@ -1,6 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Text; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using JetBrains.Annotations; namespace UnitsNet.Tests diff --git a/UnitsNet.Tests/EnumUtils.cs b/UnitsNet.Tests/EnumUtils.cs index 305b92a1c6..dc49cce56e 100644 --- a/UnitsNet.Tests/EnumUtils.cs +++ b/UnitsNet.Tests/EnumUtils.cs @@ -10,7 +10,7 @@ public static class EnumUtils { public static T[] GetEnumValues() { - return Enum.GetValues(typeof (T)).Cast().ToArray(); + return Enum.GetValues(typeof(T)).Cast().ToArray(); } } } diff --git a/UnitsNet.Tests/GeneratedQuantityCodeTests.cs b/UnitsNet.Tests/GeneratedQuantityCodeTests.cs index 4f188897f4..d4b7901b21 100644 --- a/UnitsNet.Tests/GeneratedQuantityCodeTests.cs +++ b/UnitsNet.Tests/GeneratedQuantityCodeTests.cs @@ -1,4 +1,7 @@ -using Xunit; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using Xunit; namespace UnitsNet.Tests { @@ -21,11 +24,13 @@ public void LengthEquals_GivenMaxError_ReturnsTrueIfWithinError() var smallError = 1e-5; Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), 0, ComparisonType.Relative), "Integer values have zero difference."); - Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), smallError, ComparisonType.Relative), "Using a max difference value should not change that fact."); + Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), smallError, ComparisonType.Relative), + "Using a max difference value should not change that fact."); Assert.False(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), 0, ComparisonType.Relative), "Example of floating precision arithmetic that produces slightly different results."); - Assert.True(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), smallError, ComparisonType.Relative), "But the difference is very small"); + Assert.True(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), smallError, ComparisonType.Relative), + "But the difference is very small"); } } } diff --git a/UnitsNet.Tests/Helpers/TypeDescriptorContext.cs b/UnitsNet.Tests/Helpers/TypeDescriptorContext.cs index 28e1979d88..7ef72c614e 100644 --- a/UnitsNet.Tests/Helpers/TypeDescriptorContext.cs +++ b/UnitsNet.Tests/Helpers/TypeDescriptorContext.cs @@ -2,22 +2,45 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Text; namespace UnitsNet.Tests.Helpers { /// - /// Is used to imitate e property with attributes + /// Is used to imitate e property with attributes /// public class TypeDescriptorContext : ITypeDescriptorContext { + public TypeDescriptorContext(string name, Attribute[] attributes) + { + PropertyDescriptor = new PropertyDescriptor_(name, attributes); + } + + public IContainer Container => throw new NotImplementedException(); + + public object Instance => throw new NotImplementedException(); + + public PropertyDescriptor PropertyDescriptor { get; set; } + + public object GetService(Type serviceType) + { + throw new NotImplementedException(); + } + + public void OnComponentChanged() + { + throw new NotImplementedException(); + } + + public bool OnComponentChanging() + { + throw new NotImplementedException(); + } + public class PropertyDescriptor_ : PropertyDescriptor { public PropertyDescriptor_(string name, Attribute[] attributes) : base(name, attributes) { - } public override Type ComponentType => throw new NotImplementedException(); @@ -51,31 +74,5 @@ public override bool ShouldSerializeValue(object component) throw new NotImplementedException(); } } - - public TypeDescriptorContext(string name, Attribute[] attributes) - { - PropertyDescriptor = new PropertyDescriptor_(name, attributes); - } - - public IContainer Container => throw new NotImplementedException(); - - public object Instance => throw new NotImplementedException(); - - public PropertyDescriptor PropertyDescriptor { get; set; } - - public object GetService(Type serviceType) - { - throw new NotImplementedException(); - } - - public void OnComponentChanged() - { - throw new NotImplementedException(); - } - - public bool OnComponentChanging() - { - throw new NotImplementedException(); - } } } diff --git a/UnitsNet.Tests/IntOverloadTests.cs b/UnitsNet.Tests/IntOverloadTests.cs index bf63007ba7..8cb75efa61 100644 --- a/UnitsNet.Tests/IntOverloadTests.cs +++ b/UnitsNet.Tests/IntOverloadTests.cs @@ -10,14 +10,14 @@ public class IntOverloadTests [Fact] public static void CreatingQuantityWithDoubleBackingFieldFromIntReturnsCorrectValue() { - Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(1); + var acceleration = Acceleration.FromMetersPerSecondSquared(1); Assert.Equal(1.0, acceleration.MetersPerSecondSquared); } [Fact] public static void CreatingQuantityWithIntBackingFieldFromIntReturnsCorrectValue() { - Power power = Power.FromWatts(1); + var power = Power.FromWatts(1); Assert.Equal(1.0, power.Watts); } } diff --git a/UnitsNet.Tests/InterUnitConversionTests.cs b/UnitsNet.Tests/InterUnitConversionTests.cs index d19bd70de0..cf8a89ef6d 100644 --- a/UnitsNet.Tests/InterUnitConversionTests.cs +++ b/UnitsNet.Tests/InterUnitConversionTests.cs @@ -10,16 +10,16 @@ public class InterUnitConversionTests [Fact] public void KilogramForceToKilogram() { - Force force = Force.FromKilogramsForce(1); - Mass mass = Mass.FromGravitationalForce(force); + var force = Force.FromKilogramsForce(1); + var mass = Mass.FromGravitationalForce(force); Assert.Equal(mass.Kilograms, force.KilogramsForce); } [Fact] public void KilogramToKilogramForce() { - Mass mass = Mass.FromKilograms(1); - Force force = Force.FromKilogramsForce(mass.Kilograms); + var mass = Mass.FromKilograms(1); + var force = Force.FromKilogramsForce(mass.Kilograms); Assert.Equal(mass.Kilograms, force.KilogramsForce); } } diff --git a/UnitsNet.Tests/LongOverloadTests.cs b/UnitsNet.Tests/LongOverloadTests.cs index fd54377f08..c310c7209e 100644 --- a/UnitsNet.Tests/LongOverloadTests.cs +++ b/UnitsNet.Tests/LongOverloadTests.cs @@ -10,14 +10,14 @@ public class LongOverloadTests [Fact] public static void CreatingQuantityWithDoubleBackingFieldFromLongReturnsCorrectValue() { - Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(1L); + var acceleration = Acceleration.FromMetersPerSecondSquared(1L); Assert.Equal(1.0, acceleration.MetersPerSecondSquared); } [Fact] public static void CreatingQuantityWithLongBackingFieldFromLongReturnsCorrectValue() { - Power power = Power.FromWatts(1L); + var power = Power.FromWatts(1L); Assert.Equal(1.0, power.Watts); } } diff --git a/UnitsNet.Tests/QuantityIConvertibleTests.cs b/UnitsNet.Tests/QuantityIConvertibleTests.cs index 698d4ce9b9..a55910af3f 100644 --- a/UnitsNet.Tests/QuantityIConvertibleTests.cs +++ b/UnitsNet.Tests/QuantityIConvertibleTests.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using System.Globalization; using UnitsNet.Units; using Xunit; @@ -8,7 +11,7 @@ namespace UnitsNet.Tests public class QuantityIConvertibleTests { private static Length length = Length.FromMeters(3.0); - private static IConvertible lengthAsIConvertible = Length.FromMeters(3.0); + private static readonly IConvertible lengthAsIConvertible = Length.FromMeters(3.0); [Fact] public void GetTypeCodeTest() @@ -62,7 +65,7 @@ public void ToDecimalTest() [Fact] public void ToDoubleTest() { - double expected = 3.0; + var expected = 3.0; Assert.Equal(expected, lengthAsIConvertible.ToDouble(null)); Assert.Equal(expected, Convert.ToDouble(length)); Assert.Equal(expected, Convert.ChangeType(length, typeof(double))); @@ -80,7 +83,7 @@ public void ToInt16Test() [Fact] public void ToInt32Test() { - int expected = 3; + var expected = 3; Assert.Equal(expected, lengthAsIConvertible.ToInt32(null)); Assert.Equal(expected, Convert.ToInt32(length)); Assert.Equal(expected, Convert.ChangeType(length, typeof(int))); @@ -116,7 +119,7 @@ public void ToSingleTest() [Fact] public void ToStringTest() { - string expected = length.ToString(CultureInfo.CurrentUICulture); + var expected = length.ToString(CultureInfo.CurrentUICulture); Assert.Equal(expected, lengthAsIConvertible.ToString(CultureInfo.CurrentUICulture)); Assert.Equal(expected, Convert.ToString(length, CultureInfo.CurrentUICulture)); Assert.Equal(expected, Convert.ChangeType(length, typeof(string), CultureInfo.CurrentUICulture)); diff --git a/UnitsNet.Tests/QuantityIFormattableTests.cs b/UnitsNet.Tests/QuantityIFormattableTests.cs index 059b5b22e2..3e403808b5 100644 --- a/UnitsNet.Tests/QuantityIFormattableTests.cs +++ b/UnitsNet.Tests/QuantityIFormattableTests.cs @@ -11,17 +11,17 @@ public class QuantityIFormattableTests { private static Length length = Length.FromFeet(1.2345678); - [Fact] - public void GFormatStringEqualsToString() - { - Assert.Equal(length.ToString("g"), length.ToString()); - } - - [Fact] - public void EmptyOrNullFormatStringEqualsGFormat() + [Theory] + [InlineData("s", "1 ft")] + [InlineData("s1", "1.2 ft")] + [InlineData("s2", "1.23 ft")] + [InlineData("s3", "1.235 ft")] + [InlineData("s4", "1.2346 ft")] + [InlineData("s5", "1.23457 ft")] + [InlineData("s6", "1.234568 ft")] + public void SFormatEqualsSignificantDigits(string sFormatString, string expected) { - Assert.Equal(length.ToString("g"), length.ToString(string.Empty)); - Assert.Equal(length.ToString("g"), length.ToString((string)null)); + Assert.Equal(expected, length.ToString(sFormatString, NumberFormatInfo.InvariantInfo)); } [Fact] @@ -41,28 +41,22 @@ public void AFormatWithInvalidIndexThrowsFormatException() } [Fact] - public void VFormatEqualsValueToString() + public void EmptyOrNullFormatStringEqualsGFormat() { - Assert.Equal(length.Value.ToString(CultureInfo.CurrentUICulture), length.ToString("v")); + Assert.Equal(length.ToString("g"), length.ToString(string.Empty)); + Assert.Equal(length.ToString("g"), length.ToString((string) null)); } [Fact] - public void QFormatEqualsQuantityName() + public void GFormatStringEqualsToString() { - Assert.Equal(Length.Info.Name, length.ToString("q")); + Assert.Equal(length.ToString("g"), length.ToString()); } - [Theory] - [InlineData("s", "1 ft")] - [InlineData("s1", "1.2 ft")] - [InlineData("s2", "1.23 ft")] - [InlineData("s3", "1.235 ft")] - [InlineData("s4", "1.2346 ft")] - [InlineData("s5", "1.23457 ft")] - [InlineData("s6", "1.234568 ft")] - public void SFormatEqualsSignificantDigits(string sFormatString, string expected) + [Fact] + public void QFormatEqualsQuantityName() { - Assert.Equal(expected, length.ToString(sFormatString, NumberFormatInfo.InvariantInfo)); + Assert.Equal(Length.Info.Name, length.ToString("q")); } [Fact] @@ -76,5 +70,11 @@ public void UnsupportedFormatStringThrowsException() { Assert.Throws(() => length.ToString("z")); } + + [Fact] + public void VFormatEqualsValueToString() + { + Assert.Equal(length.Value.ToString(CultureInfo.CurrentUICulture), length.ToString("v")); + } } } diff --git a/UnitsNet.Tests/QuantityInfoTest.cs b/UnitsNet.Tests/QuantityInfoTest.cs index 51ab1ad90d..58d26c7e59 100644 --- a/UnitsNet.Tests/QuantityInfoTest.cs +++ b/UnitsNet.Tests/QuantityInfoTest.cs @@ -3,7 +3,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using UnitsNet.Units; using Xunit; @@ -15,7 +14,8 @@ public class QuantityInfoTest public void Constructor_AssignsProperties() { var expectedZero = Length.FromCentimeters(10); - var expectedUnitInfos = new UnitInfo[]{ + var expectedUnitInfos = new[] + { new UnitInfo(LengthUnit.Centimeter, new BaseUnits(LengthUnit.Centimeter)), new UnitInfo(LengthUnit.Kilometer, new BaseUnits(LengthUnit.Kilometer)) }; @@ -34,120 +34,108 @@ public void Constructor_AssignsProperties() // Obsolete members #pragma warning disable 618 - Assert.Equal( expectedBaseUnit, info.BaseUnit ); - Assert.Equal( new[] { "Centimeter", "Kilometer" }, info.UnitNames ); + Assert.Equal(expectedBaseUnit, info.BaseUnit); + Assert.Equal(new[] {"Centimeter", "Kilometer"}, info.UnitNames); #pragma warning restore 618 } [Fact] - public void GenericsConstructor_AssignsProperties() - { - var expectedZero = Length.FromCentimeters(10); - var expectedUnitInfos = new UnitInfo[]{ - new UnitInfo(LengthUnit.Centimeter, new BaseUnits(LengthUnit.Centimeter)), - new UnitInfo(LengthUnit.Kilometer, new BaseUnits(LengthUnit.Kilometer)) - }; - var expectedBaseUnit = LengthUnit.Centimeter; - var expectedQuantityType = QuantityType.Length; - var expectedBaseDimensions = Length.BaseDimensions; - - var info = new QuantityInfo(expectedQuantityType, expectedUnitInfos, - expectedBaseUnit, expectedZero, expectedBaseDimensions); - - Assert.Equal(expectedZero, info.Zero); - Assert.Equal("Length", info.Name); - Assert.Equal(expectedUnitInfos, info.UnitInfos); - Assert.Equal(expectedQuantityType, info.QuantityType); - Assert.Equal(expectedBaseDimensions, info.BaseDimensions); - - // Obsolete members -#pragma warning disable 618 - Assert.Equal( expectedBaseUnit, info.BaseUnit ); - Assert.Equal( new[] { "Centimeter", "Kilometer" }, info.UnitNames ); -#pragma warning restore 618 - } - - [Fact] - public void Constructor_GivenUndefinedAsQuantityType_ThrowsArgumentException() - { - Assert.Throws(() => new QuantityInfo(QuantityType.Undefined, - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); - } - - [Fact] - public void GenericsConstructor_GivenUndefinedAsQuantityType_ThrowsArgumentException() + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + public void Constructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() { - Assert.Throws(() => new QuantityInfo(QuantityType.Undefined, - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); + Assert.Throws(() => new QuantityInfo(QuantityType.Length, + Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null)); } [Fact] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() + public void Constructor_GivenNullAsBaseUnit_ThrowsArgumentNullException() { Assert.Throws(() => new QuantityInfo(QuantityType.Length, - null, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); + Length.Info.UnitInfos, null, Length.Zero, Length.BaseDimensions)); } [Fact] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() + public void Constructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() { - Assert.Throws(() => new QuantityInfo(QuantityType.Length, + Assert.Throws(() => new QuantityInfo(QuantityType.Length, null, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); } [Fact] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsBaseUnit_ThrowsArgumentNullException() + public void Constructor_GivenNullAsZero_ThrowsArgumentNullException() { Assert.Throws(() => new QuantityInfo(QuantityType.Length, - Length.Info.UnitInfos, null, Length.Zero, Length.BaseDimensions)); + Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions)); } [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsZero_ThrowsArgumentNullException() + public void Constructor_GivenUndefinedAsQuantityType_ThrowsArgumentException() { - Assert.Throws(() => new QuantityInfo(QuantityType.Length, - Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions)); + Assert.Throws(() => new QuantityInfo(QuantityType.Undefined, + Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); } [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor_GivenNullAsZero_ThrowsArgumentNullException() + public void GenericsConstructor_AssignsProperties() { - Assert.Throws(() => new QuantityInfo(QuantityType.Length, - Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions)); + var expectedZero = Length.FromCentimeters(10); + var expectedUnitInfos = new[] + { + new UnitInfo(LengthUnit.Centimeter, new BaseUnits(LengthUnit.Centimeter)), + new UnitInfo(LengthUnit.Kilometer, new BaseUnits(LengthUnit.Kilometer)) + }; + var expectedBaseUnit = LengthUnit.Centimeter; + var expectedQuantityType = QuantityType.Length; + var expectedBaseDimensions = Length.BaseDimensions; + + var info = new QuantityInfo(expectedQuantityType, expectedUnitInfos, + expectedBaseUnit, expectedZero, expectedBaseDimensions); + + Assert.Equal(expectedZero, info.Zero); + Assert.Equal("Length", info.Name); + Assert.Equal(expectedUnitInfos, info.UnitInfos); + Assert.Equal(expectedQuantityType, info.QuantityType); + Assert.Equal(expectedBaseDimensions, info.BaseDimensions); + + // Obsolete members +#pragma warning disable 618 + Assert.Equal(expectedBaseUnit, info.BaseUnit); + Assert.Equal(new[] {"Centimeter", "Kilometer"}, info.UnitNames); +#pragma warning restore 618 } [Fact] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() + public void GenericsConstructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() { - Assert.Throws(() => new QuantityInfo(QuantityType.Length, + Assert.Throws(() => new QuantityInfo(QuantityType.Length, Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null)); } [Fact] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() + public void GenericsConstructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() { Assert.Throws(() => new QuantityInfo(QuantityType.Length, - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null)); + null, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); } [Fact] - public void GetUnitInfoFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + public void GenericsConstructor_GivenNullAsZero_ThrowsArgumentNullException() { - Assert.Throws(() => Length.Info.GetUnitInfoFor(null)); + Assert.Throws(() => new QuantityInfo(QuantityType.Length, + Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions)); } [Fact] - public void GetUnitInfoFor_GivenBaseUnitsWithNoMatch_ThrowsInvalidOperationException() + public void GenericsConstructor_GivenUndefinedAsQuantityType_ThrowsArgumentException() { - var baseUnitsWithNoMatch = new BaseUnits(mass: MassUnit.Kilogram); - Assert.Throws(() => Length.Info.GetUnitInfoFor(baseUnitsWithNoMatch)); + Assert.Throws(() => new QuantityInfo(QuantityType.Undefined, + Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); } [Fact] @@ -156,34 +144,23 @@ public void GetUnitInfoFor_GivenBaseUnitsWithMultipleMatches_ThrowsInvalidOperat var baseUnits = new BaseUnits(LengthUnit.Meter); var quantityInfo = new QuantityInfo(QuantityType.Length, - new UnitInfo[]{ - new UnitInfo(LengthUnit.Meter, baseUnits), - new UnitInfo(LengthUnit.Foot, baseUnits) }, + new[] {new UnitInfo(LengthUnit.Meter, baseUnits), new UnitInfo(LengthUnit.Foot, baseUnits)}, LengthUnit.Meter, Length.Zero, Length.BaseDimensions); Assert.Throws(() => quantityInfo.GetUnitInfoFor(baseUnits)); } [Fact] - public void GetUnitInfosFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() - { - Assert.Throws(() => Length.Info.GetUnitInfosFor(null)); - } - - [Fact] - public void GetUnitInfosFor_GivenBaseUnitsWithNoMatch_ReturnsEmpty() + public void GetUnitInfoFor_GivenBaseUnitsWithNoMatch_ThrowsInvalidOperationException() { var baseUnitsWithNoMatch = new BaseUnits(mass: MassUnit.Kilogram); - var result = Length.Info.GetUnitInfosFor(baseUnitsWithNoMatch); - Assert.Empty(result); + Assert.Throws(() => Length.Info.GetUnitInfoFor(baseUnitsWithNoMatch)); } [Fact] - public void GetUnitInfosFor_GivenBaseUnitsWithOneMatch_ReturnsOneMatch() + public void GetUnitInfoFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() { - var baseUnitsWithOneMatch = new BaseUnits(LengthUnit.Foot); - var result = Length.Info.GetUnitInfosFor(baseUnitsWithOneMatch); - Assert.Collection(result, element1 => Assert.Equal(LengthUnit.Foot, element1.Value)); + Assert.Throws(() => Length.Info.GetUnitInfoFor(null)); } [Fact] @@ -192,9 +169,7 @@ public void GetUnitInfosFor_GivenBaseUnitsWithMultipleMatches_ReturnsMultipleMat var baseUnits = new BaseUnits(LengthUnit.Meter); var quantityInfo = new QuantityInfo(QuantityType.Length, - new UnitInfo[]{ - new UnitInfo(LengthUnit.Meter, baseUnits), - new UnitInfo(LengthUnit.Foot, baseUnits) }, + new[] {new UnitInfo(LengthUnit.Meter, baseUnits), new UnitInfo(LengthUnit.Foot, baseUnits)}, LengthUnit.Meter, Length.Zero, Length.BaseDimensions); var result = quantityInfo.GetUnitInfosFor(baseUnits); @@ -209,7 +184,29 @@ public void GetUnitInfosFor_GivenBaseUnitsWithMultipleMatches_ReturnsMultipleMat { Assert.Equal(LengthUnit.Foot, element2.Value); Assert.Equal(baseUnits, element2.BaseUnits); - } ); + }); + } + + [Fact] + public void GetUnitInfosFor_GivenBaseUnitsWithNoMatch_ReturnsEmpty() + { + var baseUnitsWithNoMatch = new BaseUnits(mass: MassUnit.Kilogram); + var result = Length.Info.GetUnitInfosFor(baseUnitsWithNoMatch); + Assert.Empty(result); + } + + [Fact] + public void GetUnitInfosFor_GivenBaseUnitsWithOneMatch_ReturnsOneMatch() + { + var baseUnitsWithOneMatch = new BaseUnits(LengthUnit.Foot); + var result = Length.Info.GetUnitInfosFor(baseUnitsWithOneMatch); + Assert.Collection(result, element1 => Assert.Equal(LengthUnit.Foot, element1.Value)); + } + + [Fact] + public void GetUnitInfosFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() + { + Assert.Throws(() => Length.Info.GetUnitInfosFor(null)); } } } diff --git a/UnitsNet.Tests/QuantityParserTests.cs b/UnitsNet.Tests/QuantityParserTests.cs index 79f9a7bd72..e3e5b12537 100644 --- a/UnitsNet.Tests/QuantityParserTests.cs +++ b/UnitsNet.Tests/QuantityParserTests.cs @@ -15,7 +15,7 @@ public void Parse_MappedCustomUnit() unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "fooh"); var quantityParser = new QuantityParser(unitAbbreviationsCache); - HowMuch q = quantityParser.Parse("1 fooh", + var q = quantityParser.Parse("1 fooh", null, (value, unit) => new HowMuch((double) value, unit)); @@ -30,7 +30,7 @@ public void TryParse_MappedCustomUnit() unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "fooh"); var quantityParser = new QuantityParser(unitAbbreviationsCache); - bool success = quantityParser.TryParse("1 fooh", + var success = quantityParser.TryParse("1 fooh", null, (value, unit) => new HowMuch((double) value, unit), out HowMuch q); @@ -39,6 +39,5 @@ public void TryParse_MappedCustomUnit() Assert.Equal(HowMuchUnit.Some, q.Unit); Assert.Equal(1, q.Value); } - } } diff --git a/UnitsNet.Tests/QuantityTest.cs b/UnitsNet.Tests/QuantityTest.cs index 296a01eb68..13ad4ac552 100644 --- a/UnitsNet.Tests/QuantityTest.cs +++ b/UnitsNet.Tests/QuantityTest.cs @@ -4,7 +4,6 @@ using System; using System.Globalization; using System.Linq; -using JetBrains.Annotations; using UnitsNet.Units; using Xunit; @@ -30,7 +29,7 @@ public void From_GivenNaNOrInfinity_ThrowsArgumentException(double value) [InlineData(double.NegativeInfinity)] public void TryFrom_GivenNaNOrInfinity_ReturnsFalseAndNullQuantity(double value) { - Assert.False(Quantity.TryFrom(value, LengthUnit.Centimeter, out IQuantity parsedLength)); + Assert.False(Quantity.TryFrom(value, LengthUnit.Centimeter, out var parsedLength)); Assert.Null(parsedLength); } @@ -42,6 +41,28 @@ public void From_GivenValueAndUnit_ReturnsQuantity() Assert.Equal(Pressure.FromMegabars(3), Quantity.From(3, PressureUnit.Megabar)); } + [Fact] + public void FromQuantityType_GivenInvalidQuantityType_ThrowsArgumentException() + { + Assert.Throws(() => Quantity.FromQuantityType((QuantityType) (-1), 0.0)); + } + + [Fact] + public void FromQuantityType_GivenLengthQuantityType_ReturnsLengthQuantity() + { + var fromQuantity = Quantity.FromQuantityType(QuantityType.Length, 0.0); + + Assert.Equal(0.0, fromQuantity.Value); + Assert.Equal(QuantityType.Length, fromQuantity.Type); + Assert.Equal(Length.BaseUnit, fromQuantity.Unit); + } + + [Fact] + public void FromQuantityType_GivenUndefinedQuantityType_ThrowsArgumentException() + { + Assert.Throws(() => Quantity.FromQuantityType(QuantityType.Undefined, 0.0)); + } + [Fact] public void GetInfo_GivenLength_ReturnsQuantityInfoForLength() { @@ -49,7 +70,7 @@ public void GetInfo_GivenLength_ReturnsQuantityInfoForLength() var knownLengthUnitNames = new[] {"Meter", "Centimeter", "Kilometer"}; var lengthUnitCount = Enum.GetValues(typeof(LengthUnit)).Length - 1; // Exclude LengthUnit.Undefined - QuantityInfo quantityInfo = Quantity.GetInfo(QuantityType.Length); + var quantityInfo = Quantity.GetInfo(QuantityType.Length); Assert.Equal("Length", quantityInfo.Name); Assert.Equal(QuantityType.Length, quantityInfo.QuantityType); @@ -72,7 +93,7 @@ public void GetInfo_GivenMass_ReturnsQuantityInfoForMass() var knownMassUnitNames = new[] {"Kilogram", "Gram", "Tonne"}; var massUnitCount = Enum.GetValues(typeof(MassUnit)).Length - 1; // Exclude MassUnit.Undefined - QuantityInfo quantityInfo = Quantity.GetInfo(QuantityType.Mass); + var quantityInfo = Quantity.GetInfo(QuantityType.Mass); Assert.Equal("Mass", quantityInfo.Name); Assert.Equal(QuantityType.Mass, quantityInfo.QuantityType); @@ -91,12 +112,7 @@ public void GetInfo_GivenMass_ReturnsQuantityInfoForMass() [Fact] public void Infos_ReturnsKnownQuantityInfoObjects() { - var knownQuantityInfos = new[] - { - Quantity.GetInfo(QuantityType.Length), - Quantity.GetInfo(QuantityType.Force), - Quantity.GetInfo(QuantityType.Mass) - }; + var knownQuantityInfos = new[] {Quantity.GetInfo(QuantityType.Length), Quantity.GetInfo(QuantityType.Force), Quantity.GetInfo(QuantityType.Mass)}; var infos = Quantity.Infos; @@ -126,46 +142,46 @@ public void QuantityNames_ReturnsKnownNames() [Fact] public void TryFrom_GivenValueAndUnit_ReturnsQuantity() { - Assert.True(Quantity.TryFrom(3, LengthUnit.Centimeter, out IQuantity parsedLength)); + Assert.True(Quantity.TryFrom(3, LengthUnit.Centimeter, out var parsedLength)); Assert.Equal(Length.FromCentimeters(3), parsedLength); - Assert.True(Quantity.TryFrom(3, MassUnit.Tonne, out IQuantity parsedMass)); + Assert.True(Quantity.TryFrom(3, MassUnit.Tonne, out var parsedMass)); Assert.Equal(Mass.FromTonnes(3), parsedMass); - Assert.True(Quantity.TryFrom(3, PressureUnit.Megabar, out IQuantity parsedPressure)); + Assert.True(Quantity.TryFrom(3, PressureUnit.Megabar, out var parsedPressure)); Assert.Equal(Pressure.FromMegabars(3), parsedPressure); } [Fact] public void TryParse_GivenInvalidQuantityType_ReturnsFalseAndNullQuantity() { - Assert.False(Quantity.TryParse(typeof(DummyIQuantity), "3.0 cm", out IQuantity parsedLength)); + Assert.False(Quantity.TryParse(typeof(DummyIQuantity), "3.0 cm", out var parsedLength)); Assert.Null(parsedLength); } [Fact] public void TryParse_GivenInvalidString_ReturnsFalseAndNullQuantity() { - Assert.False(Quantity.TryParse(typeof(Length), "x cm", out IQuantity parsedLength)); + Assert.False(Quantity.TryParse(typeof(Length), "x cm", out var parsedLength)); Assert.Null(parsedLength); - Assert.False(Quantity.TryParse(typeof(Mass), "xt", out IQuantity parsedMass)); + Assert.False(Quantity.TryParse(typeof(Mass), "xt", out var parsedMass)); Assert.Null(parsedMass); - Assert.False(Quantity.TryParse(typeof(Pressure), "foo", out IQuantity parsedPressure)); + Assert.False(Quantity.TryParse(typeof(Pressure), "foo", out var parsedPressure)); Assert.Null(parsedPressure); } [Fact] public void TryParse_GivenValueAndUnit_ReturnsQuantity() { - Assert.True(Quantity.TryParse(typeof(Length), "3 cm", out IQuantity parsedLength)); + Assert.True(Quantity.TryParse(typeof(Length), "3 cm", out var parsedLength)); Assert.Equal(Length.FromCentimeters(3), parsedLength); - Assert.True(Quantity.TryParse(typeof(Mass), "03t", out IQuantity parsedMass)); + Assert.True(Quantity.TryParse(typeof(Mass), "03t", out var parsedMass)); Assert.Equal(Mass.FromTonnes(3), parsedMass); - Assert.True(Quantity.TryParse(NumberFormatInfo.InvariantInfo, typeof(Pressure), "3.0 Mbar", out IQuantity parsedPressure)); + Assert.True(Quantity.TryParse(NumberFormatInfo.InvariantInfo, typeof(Pressure), "3.0 Mbar", out var parsedPressure)); Assert.Equal(Pressure.FromMegabars(3), parsedPressure); } @@ -179,27 +195,5 @@ public void Types_ReturnsKnownQuantityTypes() Assert.Superset(knownQuantities.ToHashSet(), types.ToHashSet()); Assert.Equal(QuantityCount, types.Length); } - - [Fact] - public void FromQuantityType_GivenUndefinedQuantityType_ThrowsArgumentException() - { - Assert.Throws(() => Quantity.FromQuantityType(QuantityType.Undefined, 0.0)); - } - - [Fact] - public void FromQuantityType_GivenInvalidQuantityType_ThrowsArgumentException() - { - Assert.Throws(() => Quantity.FromQuantityType((QuantityType)(-1), 0.0)); - } - - [Fact] - public void FromQuantityType_GivenLengthQuantityType_ReturnsLengthQuantity() - { - var fromQuantity = Quantity.FromQuantityType(QuantityType.Length, 0.0); - - Assert.Equal(0.0, fromQuantity.Value); - Assert.Equal(QuantityType.Length, fromQuantity.Type); - Assert.Equal(Length.BaseUnit, fromQuantity.Unit); - } } } diff --git a/UnitsNet.Tests/QuantityTests.Ctor.cs b/UnitsNet.Tests/QuantityTests.Ctor.cs index 869a3df951..263ba43897 100644 --- a/UnitsNet.Tests/QuantityTests.Ctor.cs +++ b/UnitsNet.Tests/QuantityTests.Ctor.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using System.Diagnostics.CodeAnalysis; using JetBrains.Annotations; using UnitsNet.Units; @@ -10,99 +13,14 @@ namespace UnitsNet.Tests public partial class QuantityTests { /// - /// Tests constructors of quantity types. + /// 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, MassUnit.Kilogram).Value); - Assert.Equal(5, new Mass(5d, MassUnit.Kilogram).Value); - Assert.Equal(MassUnit.Kilogram, new Mass(5L, MassUnit.Kilogram).Unit); - Assert.Equal(MassUnit.Kilogram, new Mass(5d, MassUnit.Kilogram).Unit); - - // decimal types - Assert.Equal(5, new Information(5L, InformationUnit.Bit).Value); - Assert.Equal(5, new Information(5m, InformationUnit.Bit).Value); - Assert.Equal(InformationUnit.Bit, new Information(5L, InformationUnit.Bit).Unit); - Assert.Equal(InformationUnit.Bit, new Information(5m, InformationUnit.Bit).Unit); - - // logarithmic types - Assert.Equal(5, new Level(5L, LevelUnit.Decibel).Value); - Assert.Equal(5, new Level(5d, LevelUnit.Decibel).Value); - Assert.Equal(LevelUnit.Decibel, new Level(5L, LevelUnit.Decibel).Unit); - Assert.Equal(LevelUnit.Decibel, new Level(5d, LevelUnit.Decibel).Unit); -#pragma warning restore 618 - } - - [Fact] - public void CtorWithValueAndUnitOfRepresentativeTypes_SetsValueAndUnit() + private static void AssertUnitValue(IQuantity actual, double expectedValue, Enum expectedUnit) { - // 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); + Assert.Equal(expectedValue, actual.Value); + Assert.Equal(expectedUnit, actual.Unit); } [Fact] @@ -112,12 +30,12 @@ public void Constructor_UnitSystemGivenNull_ThrowsArgumentNullException() } /// - /// This test shows what quantities support the SI UnitSystem, which is not many. - /// UnitSystem is still experimental and this design will probably change at some point as we see problems with ambiguity - /// as well as representing anything else but the SI unit system like CGS or British Engineering Units. - /// - /// Extending the functionality of BaseUnits & UnitSystem · Issue #651 · angularsen/UnitsNet - /// https://github.com/angularsen/UnitsNet/issues/651 + /// This test shows what quantities support the SI UnitSystem, which is not many. + /// UnitSystem is still experimental and this design will probably change at some point as we see problems with + /// ambiguity + /// as well as representing anything else but the SI unit system like CGS or British Engineering Units. + /// Extending the functionality of BaseUnits & UnitSystem · Issue #651 · angularsen/UnitsNet + /// https://github.com/angularsen/UnitsNet/issues/651 /// [Fact] public void Ctor_WithValueAndSIUnitSystem_ReturnsQuantityWithSIUnitOrThrowsArgumentExceptionIfNotImplemented() @@ -219,10 +137,97 @@ public void Ctor_WithValueAndSIUnitSystem_ReturnsQuantityWithSIUnitOrThrowsArgum Assert.Throws(() => new Volume(1, UnitSystem.SI)); } - private static void AssertUnitValue(IQuantity actual, double expectedValue, Enum expectedUnit) + [Fact] + public void CtorWithOnlyValueOfRepresentativeTypes_SetsValueToGivenValueAndUnitToBaseUnit() { - Assert.Equal(expectedValue, actual.Value); - Assert.Equal(expectedUnit, actual.Unit); +#pragma warning disable 618 + // double types + Assert.Equal(5, new Mass(5L, MassUnit.Kilogram).Value); + Assert.Equal(5, new Mass(5d, MassUnit.Kilogram).Value); + Assert.Equal(MassUnit.Kilogram, new Mass(5L, MassUnit.Kilogram).Unit); + Assert.Equal(MassUnit.Kilogram, new Mass(5d, MassUnit.Kilogram).Unit); + + // decimal types + Assert.Equal(5, new Information(5L, InformationUnit.Bit).Value); + Assert.Equal(5, new Information(5m, InformationUnit.Bit).Value); + Assert.Equal(InformationUnit.Bit, new Information(5L, InformationUnit.Bit).Unit); + Assert.Equal(InformationUnit.Bit, new Information(5m, InformationUnit.Bit).Unit); + + // logarithmic types + Assert.Equal(5, new Level(5L, LevelUnit.Decibel).Value); + Assert.Equal(5, new Level(5d, LevelUnit.Decibel).Value); + Assert.Equal(LevelUnit.Decibel, new Level(5L, LevelUnit.Decibel).Unit); + Assert.Equal(LevelUnit.Decibel, new Level(5d, LevelUnit.Decibel).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); + } + + [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(); + } + + /// + /// 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 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); } } } diff --git a/UnitsNet.Tests/QuantityTests.ToString.cs b/UnitsNet.Tests/QuantityTests.ToString.cs index e261daa6c6..5d68dbc5d2 100644 --- a/UnitsNet.Tests/QuantityTests.ToString.cs +++ b/UnitsNet.Tests/QuantityTests.ToString.cs @@ -14,16 +14,21 @@ public partial class QuantityTests public class ToStringTests { [Fact] - public void CreatedByDefaultCtor_ReturnsValueInBaseUnit() + public void ConvertsToTheGivenUnit() { - // 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()); + var oldCulture = CultureInfo.CurrentUICulture; + try + { + CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + Assert.Equal("5,000 g", Mass.FromKilograms(5).ToUnit(MassUnit.Gram).ToString()); + Assert.Equal("5 kg", Mass.FromGrams(5000).ToUnit(MassUnit.Kilogram).ToString()); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString()); + Assert.Equal("1.97 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString()); + } + finally + { + CultureInfo.CurrentUICulture = oldCulture; + } } [Fact] @@ -60,39 +65,28 @@ public void CreatedByCtorWithValueAndUnit_ReturnsValueAndUnit() } [Fact] - public void ReturnsTheOriginalValueAndUnit() + public void CreatedByDefaultCtor_ReturnsValueInBaseUnit() { - var oldCulture = CultureInfo.CurrentUICulture; - try - { - CultureInfo.CurrentUICulture = 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 - { - CultureInfo.CurrentUICulture = oldCulture; - } + // 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 ConvertsToTheGivenUnit() + public void FormatsNumberUsingGivenCulture() { var oldCulture = CultureInfo.CurrentUICulture; try { CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; - Assert.Equal("5,000 g", Mass.FromKilograms(5).ToUnit(MassUnit.Gram).ToString()); - Assert.Equal("5 kg", Mass.FromGrams(5000).ToUnit(MassUnit.Kilogram).ToString()); - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString()); - Assert.Equal("1.97 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString()); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString((IFormatProvider) null)); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(CultureInfo.InvariantCulture)); + Assert.Equal("0,05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(new CultureInfo("nb-NO"))); } finally { @@ -101,15 +95,15 @@ public void ConvertsToTheGivenUnit() } [Fact] - public void FormatsNumberUsingGivenCulture() + public void FormatsNumberUsingGivenDigitsAfterRadix() { var oldCulture = CultureInfo.CurrentUICulture; try { CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString((IFormatProvider)null)); - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(CultureInfo.InvariantCulture)); - Assert.Equal("0,05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(new CultureInfo("nb-NO"))); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString("s4")); + Assert.Equal("1.97 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString("s2")); + Assert.Equal("1.9685 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString("s4")); } finally { @@ -118,15 +112,21 @@ public void FormatsNumberUsingGivenCulture() } [Fact] - public void FormatsNumberUsingGivenDigitsAfterRadix() + public void ReturnsTheOriginalValueAndUnit() { var oldCulture = CultureInfo.CurrentUICulture; try { CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString("s4")); - Assert.Equal("1.97 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString("s2")); - Assert.Equal("1.9685 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString("s4")); + 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 { diff --git a/UnitsNet.Tests/QuantityTests.cs b/UnitsNet.Tests/QuantityTests.cs index ab97ec0b6e..c0c5088d60 100644 --- a/UnitsNet.Tests/QuantityTests.cs +++ b/UnitsNet.Tests/QuantityTests.cs @@ -9,47 +9,47 @@ namespace UnitsNet.Tests { public partial class QuantityTests { - [Fact] - public void GetHashCodeForDifferentQuantitiesWithSameValuesAreNotEqual() + private static void AssertQuantityInfoRepresentsLength(QuantityInfo quantityInfo) { - var length = new Length(1.0, (LengthUnit)2); - var area = new Area(1.0, (AreaUnit)2); + Assert.Equal(Length.Zero, quantityInfo.Zero); + Assert.Equal("Length", quantityInfo.Name); + Assert.Equal(QuantityType.Length, quantityInfo.QuantityType); - Assert.NotEqual(length.GetHashCode(), area.GetHashCode()); + var lengthUnits = EnumUtils.GetEnumValues().Except(new[] {LengthUnit.Undefined}).ToArray(); + var lengthUnitNames = lengthUnits.Select(x => x.ToString()); + + // Obsolete members +#pragma warning disable 618 + Assert.Equal(lengthUnits, quantityInfo.Units); + Assert.Equal(lengthUnitNames, quantityInfo.UnitNames); +#pragma warning restore 618 } [Fact] - public void Length_QuantityInfo_ReturnsQuantityInfoAboutLength() + public void GetHashCodeForDifferentQuantitiesWithSameValuesAreNotEqual() { - var length = new Length(1, LengthUnit.Centimeter); + var length = new Length(1.0, (LengthUnit) 2); + var area = new Area(1.0, (AreaUnit) 2); - QuantityInfo quantityInfo = length.QuantityInfo; - - AssertQuantityInfoRepresentsLength(quantityInfo); + Assert.NotEqual(length.GetHashCode(), area.GetHashCode()); } [Fact] public void Length_Info_ReturnsQuantityInfoAboutLength() { - QuantityInfo quantityInfo = Length.Info; + var quantityInfo = Length.Info; AssertQuantityInfoRepresentsLength(quantityInfo); } - private static void AssertQuantityInfoRepresentsLength(QuantityInfo quantityInfo) + [Fact] + public void Length_QuantityInfo_ReturnsQuantityInfoAboutLength() { - Assert.Equal(Length.Zero, quantityInfo.Zero); - Assert.Equal("Length", quantityInfo.Name); - Assert.Equal(QuantityType.Length, quantityInfo.QuantityType); + var length = new Length(1, LengthUnit.Centimeter); - var lengthUnits = EnumUtils.GetEnumValues().Except(new[] {LengthUnit.Undefined}).ToArray(); - var lengthUnitNames = lengthUnits.Select(x => x.ToString()); + var quantityInfo = length.QuantityInfo; - // Obsolete members -#pragma warning disable 618 - Assert.Equal(lengthUnits, quantityInfo.Units); - Assert.Equal(lengthUnitNames, quantityInfo.UnitNames); -#pragma warning restore 618 + AssertQuantityInfoRepresentsLength(quantityInfo); } } } diff --git a/UnitsNet.Tests/QuantityTypeConverterTest.cs b/UnitsNet.Tests/QuantityTypeConverterTest.cs index 5de7b6d269..e51bea71ca 100644 --- a/UnitsNet.Tests/QuantityTypeConverterTest.cs +++ b/UnitsNet.Tests/QuantityTypeConverterTest.cs @@ -6,36 +6,38 @@ using System.Globalization; using System.Reflection; using UnitsNet.Tests.Helpers; +using UnitsNet.Units; using Xunit; namespace UnitsNet.Tests { public class QuantityTypeConverterTest { + static QuantityTypeConverterTest() + { + // NOTE: After this, you can use your TypeConverter. + AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; + } + // https://stackoverflow.com/questions/3612909/why-is-this-typeconverter-not-working private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { - AppDomain domain = (AppDomain)sender; - foreach (Assembly asm in domain.GetAssemblies()) + var domain = (AppDomain) sender; + foreach (var asm in domain.GetAssemblies()) { if (asm.FullName == args.Name) { return asm; } } - return null; - } - static QuantityTypeConverterTest() - { - // NOTE: After this, you can use your TypeConverter. - AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); + return null; } /// - /// Is used for tests that are culture dependent + /// Is used for tests that are culture dependent /// - private static CultureInfo culture = CultureInfo.GetCultureInfo("en-US"); + private static readonly CultureInfo culture = CultureInfo.GetCultureInfo("en-US"); [Theory] [InlineData(typeof(string), true)] @@ -47,7 +49,7 @@ public void CanConvertFrom_GivenSomeTypes(Type value, bool expectedResult) { var converter = new QuantityTypeConverter(); - bool canConvertFrom = converter.CanConvertFrom(value); + var canConvertFrom = converter.CanConvertFrom(value); Assert.Equal(expectedResult, canConvertFrom); } @@ -62,254 +64,237 @@ public void CanConvertTo_GivenSomeTypes(Type value, bool expectedResult) { var converter = new QuantityTypeConverter(); - bool canConvertTo = converter.CanConvertTo(value); + var canConvertTo = converter.CanConvertTo(value); Assert.Equal(expectedResult, canConvertTo); } [Theory] - [InlineData("1mm", 1, Units.LengthUnit.Millimeter)] - [InlineData("1m", 1, Units.LengthUnit.Meter)] - [InlineData("1", 1, Units.LengthUnit.Meter)] - [InlineData("1km", 1, Units.LengthUnit.Kilometer)] - public void ConvertFrom_GivenQuantityStringAndContextWithNoAttributes_ReturnsQuantityWithBaseUnitIfNotSpecified(string str, double expectedValue, Enum expectedUnit) + [InlineData("1mm", 1, LengthUnit.Millimeter)] + [InlineData("1m", 1, LengthUnit.Meter)] + [InlineData("1", 1, LengthUnit.Meter)] + [InlineData("1km", 1, LengthUnit.Kilometer)] + public void ConvertFrom_GivenQuantityStringAndContextWithNoAttributes_ReturnsQuantityWithBaseUnitIfNotSpecified(string str, double expectedValue, + Enum expectedUnit) { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - var convertedValue = (Length)converter.ConvertFrom(context, culture, str); + var convertedValue = (Length) converter.ConvertFrom(context, culture, str); Assert.Equal(expectedValue, convertedValue.Value); Assert.Equal(expectedUnit, convertedValue.Unit); } [Theory] - [InlineData("1mm", 1, Units.LengthUnit.Millimeter)] - [InlineData("1m", 1, Units.LengthUnit.Meter)] - [InlineData("1", 1, Units.LengthUnit.Centimeter)] - [InlineData("1km", 1, Units.LengthUnit.Kilometer)] - public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAttribute_ReturnsQuantityWithGivenDefaultUnitIfNotSpecified(string str, double expectedValue, Enum expectedUnit) + [InlineData("1mm", 1, LengthUnit.Millimeter)] + [InlineData("1m", 1, LengthUnit.Meter)] + [InlineData("1", 1, LengthUnit.Centimeter)] + [InlineData("1km", 1, LengthUnit.Kilometer)] + public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAttribute_ReturnsQuantityWithGivenDefaultUnitIfNotSpecified(string str, + double expectedValue, Enum expectedUnit) { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] - { - new DefaultUnitAttribute(Units.LengthUnit.Centimeter) - }); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DefaultUnitAttribute(LengthUnit.Centimeter)}); - var convertedValue = (Length)converter.ConvertFrom(context, culture, str); + var convertedValue = (Length) converter.ConvertFrom(context, culture, str); Assert.Equal(expectedValue, convertedValue.Value); Assert.Equal(expectedUnit, convertedValue.Unit); } [Theory] - [InlineData("1mm", 0.001, Units.LengthUnit.Meter)] - [InlineData("1m", 1, Units.LengthUnit.Meter)] - [InlineData("1", 0.01, Units.LengthUnit.Meter)] - [InlineData("1km", 1000, Units.LengthUnit.Meter)] - public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAndConvertToUnitAttributes_ReturnsQuantityConvertedToUnit(string str, double expectedValue, Enum expectedUnit) + [InlineData("1mm", 0.001, LengthUnit.Meter)] + [InlineData("1m", 1, LengthUnit.Meter)] + [InlineData("1", 0.01, LengthUnit.Meter)] + [InlineData("1km", 1000, LengthUnit.Meter)] + public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAndConvertToUnitAttributes_ReturnsQuantityConvertedToUnit(string str, + double expectedValue, Enum expectedUnit) { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] - { - new DefaultUnitAttribute(Units.LengthUnit.Centimeter), - new ConvertToUnitAttribute(Units.LengthUnit.Meter) - }); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", + new Attribute[] {new DefaultUnitAttribute(LengthUnit.Centimeter), new ConvertToUnitAttribute(LengthUnit.Meter)}); - var convertedValue = (Length)converter.ConvertFrom(context, culture, str); + var convertedValue = (Length) converter.ConvertFrom(context, culture, str); Assert.Equal(expectedValue, convertedValue.Value); Assert.Equal(expectedUnit, convertedValue.Unit); } - [Fact] - public void ConvertFrom_GivenEmptyString_ThrowsNotSupportedException() + [Theory] + [InlineData(typeof(Length))] + [InlineData(typeof(IQuantity))] + [InlineData(typeof(object))] + public void ConvertTo_GivenWrongType_ThrowsNotSupportedException(Type value) { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + var length = Length.FromMeters(1); - Assert.Throws(() => converter.ConvertFrom(context, culture, "")); + Assert.Throws(() => converter.ConvertTo(length, value)); } [Fact] - public void ConvertFrom_GivenWrongQuantity_ThrowsArgumentException() + public void ConvertFrom_GivenDefaultUnitAttributeWithWrongUnitType_ThrowsArgumentException() { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DefaultUnitAttribute(VolumeUnit.CubicMeter)}); - Assert.Throws(() => converter.ConvertFrom(context, culture, "1m^2")); + Assert.Throws(() => converter.ConvertFrom(context, culture, "1")); } - [Theory] - [InlineData(typeof(Length))] - [InlineData(typeof(IQuantity))] - [InlineData(typeof(object))] - public void ConvertTo_GivenWrongType_ThrowsNotSupportedException(Type value) + [Fact] + public void ConvertFrom_GivenEmptyString_ThrowsNotSupportedException() { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Length length = Length.FromMeters(1); - Assert.Throws(() => converter.ConvertTo(length, value)); + Assert.Throws(() => converter.ConvertFrom(context, culture, "")); } [Fact] - public void ConvertTo_GivenStringType_ReturnsQuantityString() + public void ConvertFrom_GivenStringWithPower_1() { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Length length = Length.FromMeters(1); - string convertedQuantity = (string)converter.ConvertTo(length, typeof(string)); - - Assert.Equal("1 m", convertedQuantity); + Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, culture, "1m")); + Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, culture, "1m^1")); } [Fact] - public void ConvertTo_GivenSomeQuantitysAndContextWithNoAttributes_ReturnsQuantityStringInUnitOfQuantity() + public void ConvertFrom_GivenStringWithPower_2() { - var converter = new QuantityTypeConverter(); + var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Length length = Length.FromMeters(1); - string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); - - Assert.Equal("1 m", convertedQuantity); + Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, culture, "1m²")); + Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, culture, "1m^2")); } [Fact] - public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUnitDefaultFormating() + public void ConvertFrom_GivenStringWithPower_3() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] - { - new DisplayAsUnitAttribute(Units.LengthUnit.Decimeter) - }); - Length length = Length.FromMeters(1); - - string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal("10 dm", convertedQuantity); + Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, culture, "1m³")); + Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, culture, "1m^3")); } [Fact] - public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUnitFormateAsValueOnly() + public void ConvertFrom_GivenStringWithPower_4() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] - { - new DisplayAsUnitAttribute(Units.LengthUnit.Decimeter, "v") - }); - Length length = Length.FromMeters(1); - - string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal("10", convertedQuantity); + Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, culture, "1m⁴")); + Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, culture, "1m^4")); } [Fact] - public void ConvertTo_TestDisplayAsFormattingWithoutDefinedUnit_ReturnsQuantityStringWithQuantetiesUnitAndFormatedAsValueOnly() + public void ConvertFrom_GivenStringWithPower_minus1() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] - { - new DisplayAsUnitAttribute(null, "v") - }); - Length length = Length.FromMeters(1); - - string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal("1", convertedQuantity); + Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, culture, "1K⁻¹")); + Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, culture, "1K^-1")); } [Fact] - public void ConvertTo_GivenSomeQuantitysAndContextWithDisplayAsUnitAttributes_ReturnsQuantityStringInSpecifiedDisplayUnit() + public void ConvertFrom_GivenStringWithPower_minus2() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] - { - new DisplayAsUnitAttribute(Units.LengthUnit.Decimeter) - }); - Length length = Length.FromMeters(1); - - string convertedQuantityDefaultCulture = (string)converter.ConvertTo(length, typeof(string)); - string convertedQuantitySpecificCulture = (string)converter.ConvertTo(context, culture, length, typeof(string)); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal("1 m", convertedQuantityDefaultCulture); - Assert.Equal("10 dm", convertedQuantitySpecificCulture); + Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg·s⁻¹·m⁻²")); + Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg·s^-1·m^-2")); + Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg*s^-1*m^-2")); } [Fact] - public void ConvertFrom_GivenDefaultUnitAttributeWithWrongUnitType_ThrowsArgumentException() + public void ConvertFrom_GivenWrongQuantity_ThrowsArgumentException() { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] - { - new DefaultUnitAttribute(Units.VolumeUnit.CubicMeter) - }); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Throws(() => converter.ConvertFrom(context, culture, "1")); + Assert.Throws(() => converter.ConvertFrom(context, culture, "1m^2")); } [Fact] - public void ConvertFrom_GivenStringWithPower_1() + public void ConvertTo_GivenSomeQuantitysAndContextWithDisplayAsUnitAttributes_ReturnsQuantityStringInSpecifiedDisplayUnit() { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DisplayAsUnitAttribute(LengthUnit.Decimeter)}); + var length = Length.FromMeters(1); - Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, culture, "1m")); - Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, culture, "1m^1")); + var convertedQuantityDefaultCulture = (string) converter.ConvertTo(length, typeof(string)); + var convertedQuantitySpecificCulture = (string) converter.ConvertTo(context, culture, length, typeof(string)); + + Assert.Equal("1 m", convertedQuantityDefaultCulture); + Assert.Equal("10 dm", convertedQuantitySpecificCulture); } [Fact] - public void ConvertFrom_GivenStringWithPower_2() + public void ConvertTo_GivenSomeQuantitysAndContextWithNoAttributes_ReturnsQuantityStringInUnitOfQuantity() { - var converter = new QuantityTypeConverter(); + var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + var length = Length.FromMeters(1); - Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, culture, "1m²")); - Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, culture, "1m^2")); + var convertedQuantity = (string) converter.ConvertTo(context, culture, length, typeof(string)); + + Assert.Equal("1 m", convertedQuantity); } [Fact] - public void ConvertFrom_GivenStringWithPower_3() + public void ConvertTo_GivenStringType_ReturnsQuantityString() { - var converter = new QuantityTypeConverter(); + var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + var length = Length.FromMeters(1); - Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, culture, "1m³")); - Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, culture, "1m^3")); + var convertedQuantity = (string) converter.ConvertTo(length, typeof(string)); + + Assert.Equal("1 m", convertedQuantity); } [Fact] - public void ConvertFrom_GivenStringWithPower_4() + public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUnitDefaultFormating() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DisplayAsUnitAttribute(LengthUnit.Decimeter)}); + var length = Length.FromMeters(1); - Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, culture, "1m⁴")); - Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, culture, "1m^4")); + var convertedQuantity = (string) converter.ConvertTo(context, culture, length, typeof(string)); + + Assert.Equal("10 dm", convertedQuantity); } [Fact] - public void ConvertFrom_GivenStringWithPower_minus1() + public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUnitFormateAsValueOnly() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = + new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DisplayAsUnitAttribute(LengthUnit.Decimeter, "v")}); + var length = Length.FromMeters(1); - Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, culture, "1K⁻¹")); - Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, culture, "1K^-1")); + var convertedQuantity = (string) converter.ConvertTo(context, culture, length, typeof(string)); + + Assert.Equal("10", convertedQuantity); } [Fact] - public void ConvertFrom_GivenStringWithPower_minus2() + public void ConvertTo_TestDisplayAsFormattingWithoutDefinedUnit_ReturnsQuantityStringWithQuantetiesUnitAndFormatedAsValueOnly() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DisplayAsUnitAttribute(null, "v")}); + var length = Length.FromMeters(1); - Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg·s⁻¹·m⁻²")); - Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg·s^-1·m^-2")); - Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg*s^-1*m^-2")); + var convertedQuantity = (string) converter.ConvertTo(context, culture, length, typeof(string)); + + Assert.Equal("1", convertedQuantity); } } } diff --git a/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs b/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs index ce7a36b980..c795ca7126 100644 --- a/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs +++ b/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs @@ -1,4 +1,7 @@ -using Xunit; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using Xunit; namespace UnitsNet.Tests { diff --git a/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs index 5103231a36..e08988a2f1 100644 --- a/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs +++ b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs @@ -2,9 +2,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; using UnitsNet.Units; using Xunit; using Xunit.Abstractions; @@ -14,6 +12,11 @@ namespace UnitsNet.Tests [Collection(nameof(UnitAbbreviationsCacheFixture))] public class UnitAbbreviationsCacheTests { + public UnitAbbreviationsCacheTests(ITestOutputHelper output) + { + _output = output; + } + private readonly ITestOutputHelper _output; private const string AmericanCultureName = "en-US"; private const string RussianCultureName = "ru-RU"; @@ -23,11 +26,6 @@ public class UnitAbbreviationsCacheTests private static readonly IFormatProvider NorwegianCulture = new CultureInfo(NorwegianCultureName); private static readonly IFormatProvider RussianCulture = new CultureInfo(RussianCultureName); - public UnitAbbreviationsCacheTests(ITestOutputHelper output) - { - _output = output; - } - // The default, parameterless ToString() method uses 2 sigifnificant digits after the radix point. [Theory] [InlineData(0, "0 m")] @@ -37,7 +35,7 @@ public UnitAbbreviationsCacheTests(ITestOutputHelper output) [InlineData(0.115, "0.12 m")] public void DefaultToStringFormatting(double value, string expected) { - string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); Assert.Equal(expected, actual); } @@ -46,6 +44,7 @@ private enum CustomUnit // ReSharper disable UnusedMember.Local Undefined = 0, Unit1, + Unit2 // ReSharper restore UnusedMember.Local } @@ -83,7 +82,7 @@ public void DecimalRadixPointCultureFormatting(string culture) [InlineData("es-MX")] public void CommaDigitGroupingCultureFormatting(string cultureName) { - CultureInfo culture = GetCulture(cultureName); + var culture = GetCulture(cultureName); Assert.Equal("1,111 m", Length.FromMeters(1111).ToUnit(LengthUnit.Meter).ToString(culture)); // Feet/Inch and Stone/Pound combinations are only used (customarily) in the US, UK and maybe Ireland - all English speaking countries. @@ -127,7 +126,7 @@ public void DecimalPointDigitGroupingCultureFormatting(string culture) public void RoundingErrorsWithSignificantDigitsAfterRadixFormatting(double value, string significantDigitsAfterRadixFormatString, string expected) { - string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(significantDigitsAfterRadixFormatString, AmericanCulture); + var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(significantDigitsAfterRadixFormatString, AmericanCulture); Assert.Equal(expected, actual); } @@ -139,7 +138,7 @@ public void RoundingErrorsWithSignificantDigitsAfterRadixFormatting(double value [InlineData(1.99e-4, "1.99e-04 m")] public void ScientificNotationLowerInterval(double value, string expected) { - string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); Assert.Equal(expected, actual); } @@ -150,7 +149,7 @@ public void ScientificNotationLowerInterval(double value, string expected) [InlineData(999.99, "999.99 m")] public void FixedPointNotationIntervalFormatting(double value, string expected) { - string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); Assert.Equal(expected, actual); } @@ -162,7 +161,7 @@ public void FixedPointNotationIntervalFormatting(double value, string expected) [InlineData(999999.99, "999,999.99 m")] public void FixedPointNotationWithDigitGroupingIntervalFormatting(double value, string expected) { - string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); Assert.Equal(expected, actual); } @@ -173,10 +172,18 @@ public void FixedPointNotationWithDigitGroupingIntervalFormatting(double value, [InlineData(double.MaxValue, "1.8e+308 m")] public void ScientificNotationUpperIntervalFormatting(double value, string expected) { - string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); Assert.Equal(expected, actual); } + /// + /// Convenience method to the proper culture parameter type. + /// + private static CultureInfo GetCulture(string cultureName) + { + return new CultureInfo(cultureName); + } + [Fact] public void AllUnitsImplementToStringForInvariantCulture() { @@ -197,47 +204,6 @@ public void AllUnitsImplementToStringForInvariantCulture() Assert.Equal("3 st 7 lb", Mass.FromStonePounds(3, 7).StonePounds.ToString()); } - [Fact] - public void ToString_WithNorwegianCulture() - { - Assert.Equal("1 °", Angle.FromDegrees(1).ToUnit(AngleUnit.Degree).ToString(NorwegianCulture)); - Assert.Equal("1 m²", Area.FromSquareMeters(1).ToUnit(AreaUnit.SquareMeter).ToString(NorwegianCulture)); - Assert.Equal("1 V", ElectricPotential.FromVolts(1).ToUnit(ElectricPotentialUnit.Volt).ToString(NorwegianCulture)); - Assert.Equal("1 m³/s", VolumeFlow.FromCubicMetersPerSecond(1).ToUnit(VolumeFlowUnit.CubicMeterPerSecond).ToString(NorwegianCulture)); - Assert.Equal("1 N", Force.FromNewtons(1).ToUnit(ForceUnit.Newton).ToString(NorwegianCulture)); - Assert.Equal("1 m", Length.FromMeters(1).ToUnit(LengthUnit.Meter).ToString(NorwegianCulture)); - Assert.Equal("1 kg", Mass.FromKilograms(1).ToUnit(MassUnit.Kilogram).ToString(NorwegianCulture)); - Assert.Equal("1 Pa", Pressure.FromPascals(1).ToUnit(PressureUnit.Pascal).ToString(NorwegianCulture)); - Assert.Equal("1 rad/s", RotationalSpeed.FromRadiansPerSecond(1).ToUnit(RotationalSpeedUnit.RadianPerSecond).ToString(NorwegianCulture)); - Assert.Equal("1 K", Temperature.FromKelvins(1).ToUnit(TemperatureUnit.Kelvin).ToString(NorwegianCulture)); - Assert.Equal("1 N·m", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(NorwegianCulture)); - Assert.Equal("1 m³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(NorwegianCulture)); - } - - [Fact] - public void ToString_WithRussianCulture() - { - Assert.Equal("1 °", Angle.FromDegrees(1).ToUnit(AngleUnit.Degree).ToString(RussianCulture)); - Assert.Equal("1 м²", Area.FromSquareMeters(1).ToUnit(AreaUnit.SquareMeter).ToString(RussianCulture)); - Assert.Equal("1 В", ElectricPotential.FromVolts(1).ToUnit(ElectricPotentialUnit.Volt).ToString(RussianCulture)); - Assert.Equal("1 м³/с", VolumeFlow.FromCubicMetersPerSecond(1).ToUnit(VolumeFlowUnit.CubicMeterPerSecond).ToString(RussianCulture)); - Assert.Equal("1 Н", Force.FromNewtons(1).ToUnit(ForceUnit.Newton).ToString(RussianCulture)); - Assert.Equal("1 м", Length.FromMeters(1).ToUnit(LengthUnit.Meter).ToString(RussianCulture)); - Assert.Equal("1 кг", Mass.FromKilograms(1).ToUnit(MassUnit.Kilogram).ToString(RussianCulture)); - Assert.Equal("1 Па", Pressure.FromPascals(1).ToUnit(PressureUnit.Pascal).ToString(RussianCulture)); - Assert.Equal("1 рад/с", RotationalSpeed.FromRadiansPerSecond(1).ToUnit(RotationalSpeedUnit.RadianPerSecond).ToString(RussianCulture)); - Assert.Equal("1 K", Temperature.FromKelvins(1).ToUnit(TemperatureUnit.Kelvin).ToString(RussianCulture)); - Assert.Equal("1 Н·м", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(RussianCulture)); - Assert.Equal("1 м³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(RussianCulture)); - } - - [Fact] - public void GetDefaultAbbreviationThrowsNotImplementedExceptionIfNoneExist() - { - var unitAbbreviationCache = new UnitAbbreviationsCache(); - Assert.Throws(() => unitAbbreviationCache.GetDefaultAbbreviation(CustomUnit.Unit1)); - } - [Fact] public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() { @@ -256,7 +222,7 @@ public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() abbreviationsCache.MapUnitToAbbreviation(CustomUnit.Unit1, AmericanCulture, "US english abbreviation for Unit1"); // Act - string abbreviation = abbreviationsCache.GetDefaultAbbreviation(CustomUnit.Unit1, zuluCulture); + var abbreviation = abbreviationsCache.GetDefaultAbbreviation(CustomUnit.Unit1, zuluCulture); // Assert Assert.Equal("US english abbreviation for Unit1", abbreviation); @@ -268,6 +234,13 @@ public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() } } + [Fact] + public void GetDefaultAbbreviationThrowsNotImplementedExceptionIfNoneExist() + { + var unitAbbreviationCache = new UnitAbbreviationsCache(); + Assert.Throws(() => unitAbbreviationCache.GetDefaultAbbreviation(CustomUnit.Unit1)); + } + [Fact] public void MapUnitToAbbreviation_AddCustomUnit_DoesNotOverrideDefaultAbbreviationForAlreadyMappedUnits() { @@ -277,6 +250,16 @@ public void MapUnitToAbbreviation_AddCustomUnit_DoesNotOverrideDefaultAbbreviati Assert.Equal("m²", cache.GetDefaultAbbreviation(AreaUnit.SquareMeter)); } + [Fact] + public void MapUnitToDefaultAbbreviation_GivenCustomAbbreviation_SetsAbbreviationUsedByQuantityToString() + { + // Use a distinct culture here so that we don't mess up other tests that may rely on the default cache. + var newZealandCulture = GetCulture("en-NZ"); + UnitAbbreviationsCache.Default.MapUnitToDefaultAbbreviation(AreaUnit.SquareMeter, newZealandCulture, "m^2"); + + Assert.Equal("1 m^2", Area.FromSquareMeters(1).ToString(newZealandCulture)); + } + [Fact] public void MapUnitToDefaultAbbreviation_GivenUnitAndCulture_SetsDefaultAbbreviationForUnitAndCulture() { @@ -287,21 +270,37 @@ public void MapUnitToDefaultAbbreviation_GivenUnitAndCulture_SetsDefaultAbbrevia } [Fact] - public void MapUnitToDefaultAbbreviation_GivenCustomAbbreviation_SetsAbbreviationUsedByQuantityToString() + public void ToString_WithNorwegianCulture() { - // Use a distinct culture here so that we don't mess up other tests that may rely on the default cache. - var newZealandCulture = GetCulture("en-NZ"); - UnitAbbreviationsCache.Default.MapUnitToDefaultAbbreviation(AreaUnit.SquareMeter, newZealandCulture, "m^2"); - - Assert.Equal("1 m^2", Area.FromSquareMeters(1).ToString(newZealandCulture)); + Assert.Equal("1 °", Angle.FromDegrees(1).ToUnit(AngleUnit.Degree).ToString(NorwegianCulture)); + Assert.Equal("1 m²", Area.FromSquareMeters(1).ToUnit(AreaUnit.SquareMeter).ToString(NorwegianCulture)); + Assert.Equal("1 V", ElectricPotential.FromVolts(1).ToUnit(ElectricPotentialUnit.Volt).ToString(NorwegianCulture)); + Assert.Equal("1 m³/s", VolumeFlow.FromCubicMetersPerSecond(1).ToUnit(VolumeFlowUnit.CubicMeterPerSecond).ToString(NorwegianCulture)); + Assert.Equal("1 N", Force.FromNewtons(1).ToUnit(ForceUnit.Newton).ToString(NorwegianCulture)); + Assert.Equal("1 m", Length.FromMeters(1).ToUnit(LengthUnit.Meter).ToString(NorwegianCulture)); + Assert.Equal("1 kg", Mass.FromKilograms(1).ToUnit(MassUnit.Kilogram).ToString(NorwegianCulture)); + Assert.Equal("1 Pa", Pressure.FromPascals(1).ToUnit(PressureUnit.Pascal).ToString(NorwegianCulture)); + Assert.Equal("1 rad/s", RotationalSpeed.FromRadiansPerSecond(1).ToUnit(RotationalSpeedUnit.RadianPerSecond).ToString(NorwegianCulture)); + Assert.Equal("1 K", Temperature.FromKelvins(1).ToUnit(TemperatureUnit.Kelvin).ToString(NorwegianCulture)); + Assert.Equal("1 N·m", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(NorwegianCulture)); + Assert.Equal("1 m³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(NorwegianCulture)); } - /// - /// Convenience method to the proper culture parameter type. - /// - private static CultureInfo GetCulture(string cultureName) + [Fact] + public void ToString_WithRussianCulture() { - return new CultureInfo(cultureName); + Assert.Equal("1 °", Angle.FromDegrees(1).ToUnit(AngleUnit.Degree).ToString(RussianCulture)); + Assert.Equal("1 м²", Area.FromSquareMeters(1).ToUnit(AreaUnit.SquareMeter).ToString(RussianCulture)); + Assert.Equal("1 В", ElectricPotential.FromVolts(1).ToUnit(ElectricPotentialUnit.Volt).ToString(RussianCulture)); + Assert.Equal("1 м³/с", VolumeFlow.FromCubicMetersPerSecond(1).ToUnit(VolumeFlowUnit.CubicMeterPerSecond).ToString(RussianCulture)); + Assert.Equal("1 Н", Force.FromNewtons(1).ToUnit(ForceUnit.Newton).ToString(RussianCulture)); + Assert.Equal("1 м", Length.FromMeters(1).ToUnit(LengthUnit.Meter).ToString(RussianCulture)); + Assert.Equal("1 кг", Mass.FromKilograms(1).ToUnit(MassUnit.Kilogram).ToString(RussianCulture)); + Assert.Equal("1 Па", Pressure.FromPascals(1).ToUnit(PressureUnit.Pascal).ToString(RussianCulture)); + Assert.Equal("1 рад/с", RotationalSpeed.FromRadiansPerSecond(1).ToUnit(RotationalSpeedUnit.RadianPerSecond).ToString(RussianCulture)); + Assert.Equal("1 K", Temperature.FromKelvins(1).ToUnit(TemperatureUnit.Kelvin).ToString(RussianCulture)); + Assert.Equal("1 Н·м", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(RussianCulture)); + Assert.Equal("1 м³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(RussianCulture)); } } } diff --git a/UnitsNet.Tests/UnitConverterTest.cs b/UnitsNet.Tests/UnitConverterTest.cs index c94ef6159e..2d198b428c 100644 --- a/UnitsNet.Tests/UnitConverterTest.cs +++ b/UnitsNet.Tests/UnitConverterTest.cs @@ -10,88 +10,6 @@ namespace UnitsNet.Tests { public class UnitConverterTest { - [Fact] - public void CustomConversionWithSameQuantityType() - { - Length ConversionFunction(Length from) => Length.FromInches(18); - - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, ConversionFunction); - - var foundConversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Inch); - var converted = foundConversionFunction(Length.FromMeters(1.0)); - - Assert.Equal(Length.FromInches(18), converted); - } - - [Fact] - public void CustomConversionWithSameQuantityTypeByTypeParam() - { - Length ConversionFunction(Length from) => Length.FromInches(18); - - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, (ConversionFunction) ConversionFunction); - - var foundConversionFunction = unitConverter.GetConversionFunction(typeof(Length), LengthUnit.Meter, typeof(Length), LengthUnit.Inch); - var converted = foundConversionFunction(Length.FromMeters(1.0)); - - Assert.Equal(Length.FromInches(18), converted); - } - - [Fact] - public void CustomConversionWithDifferentQuantityTypes() - { - IQuantity ConversionFunction(IQuantity from) => Length.FromInches(18); - - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(MassUnit.Grain, LengthUnit.Inch, ConversionFunction); - - var foundConversionFunction = unitConverter.GetConversionFunction(MassUnit.Grain, LengthUnit.Inch); - var converted = foundConversionFunction(Mass.FromGrains(100)); - - Assert.Equal(Length.FromInches(18), converted); - } - - [Fact] - public void CustomConversionWithDifferentQuantityTypesByTypeParam() - { - IQuantity ConversionFunction(IQuantity from) => Length.FromInches(18); - - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(MassUnit.Grain, LengthUnit.Inch, ConversionFunction); - - var foundConversionFunction = unitConverter.GetConversionFunction(typeof(Mass), MassUnit.Grain, typeof(Length), LengthUnit.Inch); - var converted = foundConversionFunction(Mass.FromGrains(100)); - - Assert.Equal(Length.FromInches(18), converted); - } - - [Fact] - public void TryCustomConversionForOilBarrelsToUsGallons() - { - Volume ConversionFunction(Volume from) => Volume.FromUsGallons(from.Value * 42); - - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.UsGallon, ConversionFunction); - - var foundConversionFunction = unitConverter.GetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.UsGallon); - var converted = foundConversionFunction(Volume.FromOilBarrels(1)); - - Assert.Equal(Volume.FromUsGallons(42), converted); - } - - [Fact] - public void ConversionToSameUnit_ReturnsSameQuantity() - { - var unitConverter = new UnitConverter(); - - var foundConversionFunction = unitConverter.GetConversionFunction(HowMuchUnit.ATon, HowMuchUnit.ATon); - var converted = foundConversionFunction(new HowMuch(39, HowMuchUnit.Some)); // Intentionally pass the wrong unit here, to test that the exact same quantity is returned - - Assert.Equal(39, converted.Value); - Assert.Equal(HowMuchUnit.Some, converted.Unit); - } - [Theory] [InlineData(1, HowMuchUnit.Some, HowMuchUnit.Some, 1)] [InlineData(1, HowMuchUnit.Some, HowMuchUnit.ATon, 2)] @@ -121,18 +39,6 @@ public void ConvertByName_ConvertsTheValueToGivenUnit(double expectedValue, doub Assert.Equal(expectedValue, UnitConverter.ConvertByName(inputValue, quantityTypeName, fromUnit, toUnit)); } - [Fact] - public void ConvertByName_QuantityCaseInsensitive() - { - Assert.Equal(0, UnitConverter.ConvertByName(0, "length", "Meter", "Centimeter")); - } - - [Fact] - public void ConvertByName_UnitTypeCaseInsensitive() - { - Assert.Equal(0, UnitConverter.ConvertByName(0, "Length", "meter", "Centimeter")); - } - [Theory] [InlineData(1, "UnknownQuantity", "Meter", "Centimeter")] public void ConvertByName_ThrowsUnitNotFoundExceptionOnUnknownQuantity(double inputValue, string quantityTypeName, string fromUnit, string toUnit) @@ -154,7 +60,7 @@ public void ConvertByName_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnit(doubl [InlineData(1, "Length", "Meter", "UnknownToUnit")] public void TryConvertByName_ReturnsFalseForInvalidInput(double inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.False(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out double result)); + Assert.False(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out var result)); Assert.Equal(0, result); } @@ -166,7 +72,7 @@ public void TryConvertByName_ReturnsFalseForInvalidInput(double inputValue, stri public void TryConvertByName_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.True(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out double result), "TryConvertByName() return value."); + Assert.True(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out var result), "TryConvertByName() return value."); Assert.Equal(expectedValue, result); } @@ -175,14 +81,16 @@ public void TryConvertByName_ReturnsTrueOnSuccessAndOutputsResult(double expecte [InlineData(100, 1, "Length", "m", "cm")] [InlineData(1, 1000, "Mass", "g", "kg")] [InlineData(1000, 1, "ElectricCurrent", "kA", "A")] - public void ConvertByAbbreviation_ConvertsTheValueToGivenUnit(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit) + public void ConvertByAbbreviation_ConvertsTheValueToGivenUnit(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, + string toUnit) { Assert.Equal(expectedValue, UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); } [Theory] [InlineData(1, "UnknownQuantity", "m", "cm")] - public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownQuantity( double inputValue, string quantityTypeName, string fromUnit, string toUnit) + public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownQuantity(double inputValue, string quantityTypeName, string fromUnit, + string toUnit) { Assert.Throws(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); } @@ -190,7 +98,8 @@ public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownQuantity( [Theory] [InlineData(1, "Length", "UnknownFromUnit", "cm")] [InlineData(1, "Length", "m", "UnknownToUnit")] - public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnitAbbreviation(double inputValue, string quantityTypeName, string fromUnit, string toUnit) + public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnitAbbreviation(double inputValue, string quantityTypeName, + string fromUnit, string toUnit) { Assert.Throws(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); } @@ -201,7 +110,7 @@ public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUn [InlineData(1, "Length", "m", "UnknownToUnit")] public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(double inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out double result)); + Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out var result)); Assert.Equal(0, result); } @@ -210,11 +119,123 @@ public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(double inputVal [InlineData(100, 1, "Length", "m", "cm")] [InlineData(1, 1000, "Mass", "g", "kg")] [InlineData(1000, 1, "ElectricCurrent", "kA", "A")] - public void TryConvertByAbbreviation_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, + public void TryConvertByAbbreviation_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, + string fromUnit, string toUnit) { - Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out double result), "TryConvertByAbbreviation() return value."); + Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out var result), + "TryConvertByAbbreviation() return value."); Assert.Equal(expectedValue, result); } + + [Fact] + public void ConversionToSameUnit_ReturnsSameQuantity() + { + var unitConverter = new UnitConverter(); + + var foundConversionFunction = unitConverter.GetConversionFunction(HowMuchUnit.ATon, HowMuchUnit.ATon); + var converted = foundConversionFunction(new HowMuch(39, + HowMuchUnit.Some)); // Intentionally pass the wrong unit here, to test that the exact same quantity is returned + + Assert.Equal(39, converted.Value); + Assert.Equal(HowMuchUnit.Some, converted.Unit); + } + + [Fact] + public void ConvertByName_QuantityCaseInsensitive() + { + Assert.Equal(0, UnitConverter.ConvertByName(0, "length", "Meter", "Centimeter")); + } + + [Fact] + public void ConvertByName_UnitTypeCaseInsensitive() + { + Assert.Equal(0, UnitConverter.ConvertByName(0, "Length", "meter", "Centimeter")); + } + + [Fact] + public void CustomConversionWithDifferentQuantityTypes() + { + IQuantity ConversionFunction(IQuantity from) + { + return Length.FromInches(18); + } + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(MassUnit.Grain, LengthUnit.Inch, ConversionFunction); + + var foundConversionFunction = unitConverter.GetConversionFunction(MassUnit.Grain, LengthUnit.Inch); + var converted = foundConversionFunction(Mass.FromGrains(100)); + + Assert.Equal(Length.FromInches(18), converted); + } + + [Fact] + public void CustomConversionWithDifferentQuantityTypesByTypeParam() + { + IQuantity ConversionFunction(IQuantity from) + { + return Length.FromInches(18); + } + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(MassUnit.Grain, LengthUnit.Inch, ConversionFunction); + + var foundConversionFunction = unitConverter.GetConversionFunction(typeof(Mass), MassUnit.Grain, typeof(Length), LengthUnit.Inch); + var converted = foundConversionFunction(Mass.FromGrains(100)); + + Assert.Equal(Length.FromInches(18), converted); + } + + [Fact] + public void CustomConversionWithSameQuantityType() + { + Length ConversionFunction(Length from) + { + return Length.FromInches(18); + } + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, ConversionFunction); + + var foundConversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Inch); + var converted = foundConversionFunction(Length.FromMeters(1.0)); + + Assert.Equal(Length.FromInches(18), converted); + } + + [Fact] + public void CustomConversionWithSameQuantityTypeByTypeParam() + { + Length ConversionFunction(Length from) + { + return Length.FromInches(18); + } + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, (ConversionFunction) ConversionFunction); + + var foundConversionFunction = unitConverter.GetConversionFunction(typeof(Length), LengthUnit.Meter, typeof(Length), LengthUnit.Inch); + var converted = foundConversionFunction(Length.FromMeters(1.0)); + + Assert.Equal(Length.FromInches(18), converted); + } + + [Fact] + public void TryCustomConversionForOilBarrelsToUsGallons() + { + Volume ConversionFunction(Volume from) + { + return Volume.FromUsGallons(from.Value * 42); + } + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.UsGallon, ConversionFunction); + + var foundConversionFunction = unitConverter.GetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.UsGallon); + var converted = foundConversionFunction(Volume.FromOilBarrels(1)); + + Assert.Equal(Volume.FromUsGallons(42), converted); + } } } diff --git a/UnitsNet.Tests/UnitMathTests.cs b/UnitsNet.Tests/UnitMathTests.cs index affc38d44b..80a4e3f49b 100644 --- a/UnitsNet.Tests/UnitMathTests.cs +++ b/UnitsNet.Tests/UnitMathTests.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using System.Collections.Generic; using UnitsNet.Units; using Xunit; @@ -28,7 +31,7 @@ public void AverageOfLengthsCalculatesCorrectly() { var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; - Length average = units.Average(LengthUnit.Centimeter); + var average = units.Average(LengthUnit.Centimeter); Assert.Equal(75, average.Value); Assert.Equal(LengthUnit.Centimeter, average.Unit); @@ -37,11 +40,7 @@ public void AverageOfLengthsCalculatesCorrectly() [Fact] public void AverageOfLengthsWithNullSelectorThrowsException() { - var units = new[] - { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) - }; + var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; Assert.Throws(() => units.Average((Func, Length>) null, LengthUnit.Centimeter)); } @@ -49,13 +48,9 @@ public void AverageOfLengthsWithNullSelectorThrowsException() [Fact] public void AverageOfLengthsWithSelectorCalculatesCorrectly() { - var units = new[] - { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) - }; + var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; - Length average = units.Average(x => x.Value, LengthUnit.Centimeter); + var average = units.Average(x => x.Value, LengthUnit.Centimeter); Assert.Equal(75, average.Value); Assert.Equal(LengthUnit.Centimeter, average.Unit); @@ -82,7 +77,7 @@ public void MaxOfLengthsCalculatesCorrectly() { var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; - Length max = units.Max(LengthUnit.Centimeter); + var max = units.Max(LengthUnit.Centimeter); Assert.Equal(100, max.Value); Assert.Equal(LengthUnit.Centimeter, max.Unit); @@ -91,11 +86,7 @@ public void MaxOfLengthsCalculatesCorrectly() [Fact] public void MaxOfLengthsWithNullSelectorThrowsException() { - var units = new[] - { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) - }; + var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; Assert.Throws(() => units.Max((Func, Length>) null, LengthUnit.Centimeter)); } @@ -103,13 +94,9 @@ public void MaxOfLengthsWithNullSelectorThrowsException() [Fact] public void MaxOfLengthsWithSelectorCalculatesCorrectly() { - var units = new[] - { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) - }; + var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; - Length max = units.Max(x => x.Value, LengthUnit.Centimeter); + var max = units.Max(x => x.Value, LengthUnit.Centimeter); Assert.Equal(100, max.Value); Assert.Equal(LengthUnit.Centimeter, max.Unit); @@ -136,7 +123,7 @@ public void MinOfLengthsCalculatesCorrectly() { var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; - Length min = units.Min(LengthUnit.Centimeter); + var min = units.Min(LengthUnit.Centimeter); Assert.Equal(50, min.Value); Assert.Equal(LengthUnit.Centimeter, min.Unit); @@ -145,11 +132,7 @@ public void MinOfLengthsCalculatesCorrectly() [Fact] public void MinOfLengthsWithNullSelectorThrowsException() { - var units = new[] - { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) - }; + var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; Assert.Throws(() => units.Min((Func, Length>) null, LengthUnit.Centimeter)); } @@ -157,13 +140,9 @@ public void MinOfLengthsWithNullSelectorThrowsException() [Fact] public void MinOfLengthsWithSelectorCalculatesCorrectly() { - var units = new[] - { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) - }; + var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; - Length min = units.Min(x => x.Value, LengthUnit.Centimeter); + var min = units.Min(x => x.Value, LengthUnit.Centimeter); Assert.Equal(50, min.Value); Assert.Equal(LengthUnit.Centimeter, min.Unit); @@ -182,7 +161,7 @@ public void SumOfEmptySourceReturnsZero() { var units = new Length[] { }; - Length sum = units.Sum(Length.BaseUnit); + var sum = units.Sum(Length.BaseUnit); Assert.Equal(Length.Zero, sum); } @@ -192,7 +171,7 @@ public void SumOfLengthsCalculatesCorrectly() { var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; - Length sum = units.Sum(LengthUnit.Centimeter); + var sum = units.Sum(LengthUnit.Centimeter); Assert.Equal(150, sum.Value); Assert.Equal(LengthUnit.Centimeter, sum.Unit); @@ -201,11 +180,7 @@ public void SumOfLengthsCalculatesCorrectly() [Fact] public void SumOfLengthsWithNullSelectorThrowsException() { - var units = new[] - { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) - }; + var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; Assert.Throws(() => units.Sum((Func, Length>) null, LengthUnit.Centimeter)); } @@ -213,13 +188,9 @@ public void SumOfLengthsWithNullSelectorThrowsException() [Fact] public void SumOfLengthsWithSelectorCalculatesCorrectly() { - var units = new[] - { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) - }; + var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; - Length sum = units.Sum(x => x.Value, LengthUnit.Centimeter); + var sum = units.Sum(x => x.Value, LengthUnit.Centimeter); Assert.Equal(150, sum.Value); Assert.Equal(LengthUnit.Centimeter, sum.Unit); diff --git a/UnitsNet.Tests/UnitParserTests.cs b/UnitsNet.Tests/UnitParserTests.cs index 08411f0a24..080449dbe5 100644 --- a/UnitsNet.Tests/UnitParserTests.cs +++ b/UnitsNet.Tests/UnitParserTests.cs @@ -26,43 +26,6 @@ public void Parse_ReturnsUnitMappedByCustomAbbreviation(string customAbbreviatio Assert.Equal(expected, actual); } - [Fact] - public void Parse_AbbreviationCaseInsensitive_Lowercase_years() - { - var abbreviation = "years"; - var expected = DurationUnit.Year365; - var parser = UnitParser.Default; - - var actual = parser.Parse(abbreviation); - - Assert.Equal(expected, actual); - } - - [Fact] - public void Parse_AbbreviationCaseInsensitive_Uppercase_Years() - { - var abbreviation = "Years"; - var expected = DurationUnit.Year365; - var parser = UnitParser.Default; - - var actual = parser.Parse(abbreviation); - - Assert.Equal(expected, actual); - } - - [Fact] - public void Parse_GivenAbbreviationsThatAreAmbiguousWhenLowerCase_ReturnsCorrectUnit() - { - Assert.Equal(PressureUnit.Megabar, Pressure.ParseUnit("Mbar")); - Assert.Equal(PressureUnit.Millibar, Pressure.ParseUnit("mbar")); - } - - [Fact] - public void Parse_UnknownAbbreviationThrowsUnitNotFoundException() - { - Assert.Throws(() => UnitParser.Default.Parse("nonexistingunit")); - } - [Theory] [InlineData("m", typeof(LengthUnit), LengthUnit.Meter)] [InlineData("m^1", typeof(LengthUnit), LengthUnit.Meter)] @@ -100,6 +63,42 @@ public void Parse_CanParseWithWithspacesInUnit(string unitAbbreviation, Type uni Assert.Equal(resultUnitType, UnitParser.Default.Parse(unitAbbreviation, unitType)); } + [Theory] + [InlineData("ng", "en-US", MassUnit.Nanogram)] + [InlineData("нг", "ru-RU", MassUnit.Nanogram)] + [InlineData("g", "en-US", MassUnit.Gram)] + [InlineData("г", "ru-RU", MassUnit.Gram)] + [InlineData("kg", "en-US", MassUnit.Kilogram)] + [InlineData("кг", "ru-RU", MassUnit.Kilogram)] + public void ParseMassUnit_GivenCulture(string str, string cultureName, Enum expectedUnit) + { + Assert.Equal(expectedUnit, UnitParser.Default.Parse(str, new CultureInfo(cultureName))); + } + + [Fact] + public void Parse_AbbreviationCaseInsensitive_Lowercase_years() + { + var abbreviation = "years"; + var expected = DurationUnit.Year365; + var parser = UnitParser.Default; + + var actual = parser.Parse(abbreviation); + + Assert.Equal(expected, actual); + } + + [Fact] + public void Parse_AbbreviationCaseInsensitive_Uppercase_Years() + { + var abbreviation = "Years"; + var expected = DurationUnit.Year365; + var parser = UnitParser.Default; + + var actual = parser.Parse(abbreviation); + + Assert.Equal(expected, actual); + } + [Fact] public void Parse_AmbiguousUnitsThrowsException() { @@ -114,16 +113,11 @@ public void Parse_AmbiguousUnitsThrowsException() Assert.Equal("Cannot parse \"pt\" since it could be either of these: DtpPoint, PrinterPoint", exception2.Message); } - [Theory] - [InlineData("ng", "en-US", MassUnit.Nanogram)] - [InlineData("нг", "ru-RU", MassUnit.Nanogram)] - [InlineData("g", "en-US", MassUnit.Gram)] - [InlineData("г", "ru-RU", MassUnit.Gram)] - [InlineData("kg", "en-US", MassUnit.Kilogram)] - [InlineData("кг", "ru-RU", MassUnit.Kilogram)] - public void ParseMassUnit_GivenCulture(string str, string cultureName, Enum expectedUnit) + [Fact] + public void Parse_GivenAbbreviationsThatAreAmbiguousWhenLowerCase_ReturnsCorrectUnit() { - Assert.Equal(expectedUnit, UnitParser.Default.Parse(str, new CultureInfo(cultureName))); + Assert.Equal(PressureUnit.Megabar, Pressure.ParseUnit("Mbar")); + Assert.Equal(PressureUnit.Millibar, Pressure.ParseUnit("mbar")); } [Fact] @@ -137,5 +131,11 @@ public void Parse_MappedCustomUnit() Assert.Equal(HowMuchUnit.Some, parsedUnit); } + + [Fact] + public void Parse_UnknownAbbreviationThrowsUnitNotFoundException() + { + Assert.Throws(() => UnitParser.Default.Parse("nonexistingunit")); + } } } diff --git a/UnitsNet.Tests/UnitSystemTests.cs b/UnitsNet.Tests/UnitSystemTests.cs index b0da0923ca..ec44fb3367 100644 --- a/UnitsNet.Tests/UnitSystemTests.cs +++ b/UnitsNet.Tests/UnitSystemTests.cs @@ -9,6 +9,28 @@ namespace UnitsNet.Tests { public class UnitSystemTests { + [Theory] + [InlineData(LengthUnit.Undefined, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, + AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Undefined, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, + LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Undefined, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, + LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Undefined, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, + LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Undefined, AmountOfSubstanceUnit.Mole, + LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, + AmountOfSubstanceUnit.Undefined, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, + LuminousIntensityUnit.Undefined)] + public void ConstructorThrowsArgumentExceptionWithUndefinedUnits(LengthUnit length, MassUnit mass, DurationUnit time, ElectricCurrentUnit current, + TemperatureUnit temperature, AmountOfSubstanceUnit amount, LuminousIntensityUnit luminousIntensity) + { + var baseUnits = new BaseUnits(length, mass, time, current, temperature, amount, luminousIntensity); + Assert.Throws(() => new UnitSystem(baseUnits)); + } + [Fact] public void ConstructorImplementedProperly() { @@ -26,23 +48,8 @@ public void ConstructorThrowsArgumentNullExceptionForNullBaseUnits() Assert.Throws(() => new UnitSystem(null)); } - [Theory] - [InlineData(LengthUnit.Undefined, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Undefined, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Undefined, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Undefined, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Undefined, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Undefined, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Undefined)] - public void ConstructorThrowsArgumentExceptionWithUndefinedUnits(LengthUnit length, MassUnit mass, DurationUnit time, ElectricCurrentUnit current, - TemperatureUnit temperature, AmountOfSubstanceUnit amount, LuminousIntensityUnit luminousIntensity) - { - var baseUnits = new BaseUnits(length, mass, time, current, temperature, amount, luminousIntensity); - Assert.Throws(() => new UnitSystem(baseUnits)); - } - [Fact] - public void EqualsObjectIsImplementedCorrectly() + public void EqualityOperatorIsImplementedCorrectly() { var unitSystem1 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); @@ -53,15 +60,23 @@ public void EqualsObjectIsImplementedCorrectly() var unitSystem3 = new UnitSystem(new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - Assert.True(unitSystem1.Equals((object)unitSystem2)); - Assert.False(unitSystem1.Equals((object)unitSystem3)); + Assert.True(unitSystem1 == unitSystem2); + Assert.True(unitSystem2 == unitSystem1); - Assert.False(unitSystem1.Equals("Some object.")); - Assert.False(unitSystem1.Equals((IFormatProvider)null)); + Assert.False(unitSystem1 == unitSystem3); + Assert.False(unitSystem3 == unitSystem1); + + Assert.False(unitSystem1 == null); + Assert.False(null == unitSystem1); + + UnitSystem nullUnitSystem1 = null; + UnitSystem nullUnitSystem2 = null; + + Assert.True(nullUnitSystem1 == nullUnitSystem2); } [Fact] - public void EqualsUnitSystemIsImplementedCorrectly() + public void EqualsObjectIsImplementedCorrectly() { var unitSystem1 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); @@ -72,17 +87,15 @@ public void EqualsUnitSystemIsImplementedCorrectly() var unitSystem3 = new UnitSystem(new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - Assert.True(unitSystem1.Equals(unitSystem2)); - Assert.True(unitSystem2.Equals(unitSystem1)); + Assert.True(unitSystem1.Equals((object) unitSystem2)); + Assert.False(unitSystem1.Equals((object) unitSystem3)); - Assert.False(unitSystem1.Equals(unitSystem3)); - Assert.False(unitSystem3.Equals(unitSystem1)); - - Assert.False(unitSystem1.Equals(null)); + Assert.False(unitSystem1.Equals("Some object.")); + Assert.False(unitSystem1.Equals((IFormatProvider) null)); } [Fact] - public void EqualityOperatorIsImplementedCorrectly() + public void EqualsUnitSystemIsImplementedCorrectly() { var unitSystem1 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); @@ -93,19 +106,13 @@ public void EqualityOperatorIsImplementedCorrectly() var unitSystem3 = new UnitSystem(new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - Assert.True(unitSystem1 == unitSystem2); - Assert.True(unitSystem2 == unitSystem1); - - Assert.False(unitSystem1 == unitSystem3); - Assert.False(unitSystem3 == unitSystem1); - - Assert.False(unitSystem1 == null); - Assert.False(null == unitSystem1); + Assert.True(unitSystem1.Equals(unitSystem2)); + Assert.True(unitSystem2.Equals(unitSystem1)); - UnitSystem nullUnitSystem1 = null; - UnitSystem nullUnitSystem2 = null; + Assert.False(unitSystem1.Equals(unitSystem3)); + Assert.False(unitSystem3.Equals(unitSystem1)); - Assert.True(nullUnitSystem1 == nullUnitSystem2); + Assert.False(unitSystem1.Equals(null)); } [Fact] diff --git a/UnitsNet/AssemblyInfo.cs b/UnitsNet/AssemblyInfo.cs index d897374117..4d58eaa273 100644 --- a/UnitsNet/AssemblyInfo.cs +++ b/UnitsNet/AssemblyInfo.cs @@ -5,5 +5,6 @@ using System.Runtime.CompilerServices; [assembly: CLSCompliant(true)] -[assembly: InternalsVisibleTo("UnitsNet.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010089abdcb0025f7d1c4c766686dd852b978ca5bb9fd80bba9d3539e8399b01170ae0ea10c0c3baa301b1d13090d5aff770532de00c88b67c4b24669fde7f9d87218f1c6c073a09016cbb2f87119b94227c2301f4e2a096043e30f7c47c872bbd8e0b80d924952e6b36990f13f847e83e9efb107ec2121fe39d7edaaa4e235af8c4")] - +[assembly: + InternalsVisibleTo( + "UnitsNet.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010089abdcb0025f7d1c4c766686dd852b978ca5bb9fd80bba9d3539e8399b01170ae0ea10c0c3baa301b1d13090d5aff770532de00c88b67c4b24669fde7f9d87218f1c6c073a09016cbb2f87119b94227c2301f4e2a096043e30f7c47c872bbd8e0b80d924952e6b36990f13f847e83e9efb107ec2121fe39d7edaaa4e235af8c4")] diff --git a/UnitsNet/BaseDimensions.cs b/UnitsNet/BaseDimensions.cs index 1b2f8c70ff..4ceb5f9800 100644 --- a/UnitsNet/BaseDimensions.cs +++ b/UnitsNet/BaseDimensions.cs @@ -2,8 +2,8 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using System.Text; using System.Linq; +using System.Text; namespace UnitsNet { @@ -25,18 +25,58 @@ public BaseDimensions(int length, int mass, int time, int current, int temperatu } /// - /// Checks if the dimensions represent a base quantity. + /// Gets the length dimensions (L). + /// + public int Length { get; } + + /// + /// Gets the mass dimensions (M). + /// + public int Mass { get; } + + /// + /// Gets the time dimensions (T). + /// + public int Time { get; } + + /// + /// Gets the electric current dimensions (I). + /// + public int Current { get; } + + /// + /// Gets the temperature dimensions (Θ). + /// + public int Temperature { get; } + + /// + /// Gets the amount of substance dimensions (N). + /// + public int Amount { get; } + + /// + /// Gets the luminous intensity dimensions (J). + /// + public int LuminousIntensity { get; } + + /// + /// Represents a dimensionless (unitless) quantity. + /// + public static BaseDimensions Dimensionless { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 0); + + /// + /// Checks if the dimensions represent a base quantity. /// /// True if the dimensions represent a base quantity, otherwise false. public bool IsBaseQuantity() { - var dimensionsArray = new int[]{Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}; - bool onlyOneEqualsOne = dimensionsArray.Where(dimension => dimension == 1).Take(2).Count() == 1; + var dimensionsArray = new[] {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}; + var onlyOneEqualsOne = dimensionsArray.Where(dimension => dimension == 1).Take(2).Count() == 1; return onlyOneEqualsOne; } /// - /// Checks if the dimensions represent a derived quantity. + /// Checks if the dimensions represent a derived quantity. /// /// True if the dimensions represent a derived quantity, otherwise false. public bool IsDerivedQuantity() @@ -45,7 +85,7 @@ public bool IsDerivedQuantity() } /// - /// Checks if this base dimensions object represents a dimensionless quantity. + /// Checks if this base dimensions object represents a dimensionless quantity. /// /// True if this object represents a dimensionless quantity, otherwise false. public bool IsDimensionless() @@ -56,35 +96,48 @@ public bool IsDimensionless() /// public override bool Equals(object obj) { - if(obj is null || !(obj is BaseDimensions)) + if (obj is null || !(obj is BaseDimensions)) + { return false; + } - var other = (BaseDimensions)obj; + var other = (BaseDimensions) obj; return Length == other.Length && - Mass == other.Mass && - Time == other.Time && - Current == other.Current && - Temperature == other.Temperature && - Amount == other.Amount && - LuminousIntensity == other.LuminousIntensity; + Mass == other.Mass && + Time == other.Time && + Current == other.Current && + Temperature == other.Temperature && + Amount == other.Amount && + LuminousIntensity == other.LuminousIntensity; } /// public override int GetHashCode() { - return new {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}.GetHashCode(); + return new + { + Length, + Mass, + Time, + Current, + Temperature, + Amount, + LuminousIntensity + }.GetHashCode(); } /// - /// Get resulting dimensions after multiplying two dimensions, by performing addition of each dimension. + /// Get resulting dimensions after multiplying two dimensions, by performing addition of each dimension. /// /// Other dimensions. /// Resulting dimensions. public BaseDimensions Multiply(BaseDimensions right) { - if(right is null) + if (right is null) + { throw new ArgumentNullException(nameof(right)); + } return new BaseDimensions( Length + right.Length, @@ -97,14 +150,16 @@ public BaseDimensions Multiply(BaseDimensions right) } /// - /// Get resulting dimensions after dividing two dimensions, by performing subtraction of each dimension. + /// Get resulting dimensions after dividing two dimensions, by performing subtraction of each dimension. /// /// Other dimensions. /// Resulting dimensions. public BaseDimensions Divide(BaseDimensions right) { - if(right is null) + if (right is null) + { throw new ArgumentNullException(nameof(right)); + } return new BaseDimensions( Length - right.Length, @@ -117,7 +172,7 @@ public BaseDimensions Divide(BaseDimensions right) } /// - /// Check if two dimensions are equal. + /// Check if two dimensions are equal. /// /// Left. /// Right. @@ -128,7 +183,7 @@ public BaseDimensions Divide(BaseDimensions right) } /// - /// Check if two dimensions are unequal. + /// Check if two dimensions are unequal. /// /// Left. /// Right. @@ -139,33 +194,43 @@ public BaseDimensions Divide(BaseDimensions right) } /// - /// Multiply two dimensions. + /// Multiply two dimensions. /// /// Left. /// Right. /// Resulting dimensions. public static BaseDimensions operator *(BaseDimensions left, BaseDimensions right) { - if(left is null) + if (left is null) + { throw new ArgumentNullException(nameof(left)); - else if(right is null) + } + + if (right is null) + { throw new ArgumentNullException(nameof(right)); + } return left.Multiply(right); } /// - /// Divide two dimensions. + /// Divide two dimensions. /// /// Left. /// Right. /// Resulting dimensions. public static BaseDimensions operator /(BaseDimensions left, BaseDimensions right) { - if(left is null) + if (left is null) + { throw new ArgumentNullException(nameof(left)); - else if(right is null) + } + + if (right is null) + { throw new ArgumentNullException(nameof(right)); + } return left.Divide(right); } @@ -190,53 +255,15 @@ private static void AppendDimensionString(StringBuilder sb, string name, int val { var absoluteValue = Math.Abs(value); - if(absoluteValue > 0) + if (absoluteValue > 0) { sb.AppendFormat("[{0}]", name); - if(absoluteValue > 1) + if (absoluteValue > 1) + { sb.AppendFormat("^{0}", value); + } } } - - /// - /// Gets the length dimensions (L). - /// - public int Length { get; } - - /// - /// Gets the mass dimensions (M). - /// - public int Mass{ get; } - - /// - /// Gets the time dimensions (T). - /// - public int Time{ get; } - - /// - /// Gets the electric current dimensions (I). - /// - public int Current{ get; } - - /// - /// Gets the temperature dimensions (Θ). - /// - public int Temperature{ get; } - - /// - /// Gets the amount of substance dimensions (N). - /// - public int Amount{ get; } - - /// - /// Gets the luminous intensity dimensions (J). - /// - public int LuminousIntensity{ get; } - - /// - /// Represents a dimensionless (unitless) quantity. - /// - public static BaseDimensions Dimensionless { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 0); } } diff --git a/UnitsNet/BaseUnits.cs b/UnitsNet/BaseUnits.cs index cfcf559eb1..0b1cc5f971 100644 --- a/UnitsNet/BaseUnits.cs +++ b/UnitsNet/BaseUnits.cs @@ -12,16 +12,11 @@ namespace UnitsNet /// Represents the base units for a quantity. All quantities, both base and derived, can be /// represented by a combination of these seven base units. /// - public sealed class BaseUnits: IEquatable + public sealed class BaseUnits : IEquatable { /// - /// Represents BaseUnits that have not been defined. - /// - public static BaseUnits Undefined { get; } = new BaseUnits(); - - /// - /// Creates an instance of if the base units class that represents the base units for a quantity. - /// All quantities, both base and derived, can be represented by a combination of these seven base units. + /// Creates an instance of if the base units class that represents the base units for a quantity. + /// All quantities, both base and derived, can be represented by a combination of these seven base units. /// /// The length unit (L). /// The mass unit (M). @@ -48,92 +43,154 @@ public BaseUnits( LuminousIntensity = luminousIntensity; IsFullyDefined = Length != LengthUnit.Undefined && - Mass != MassUnit.Undefined && - Time != DurationUnit.Undefined && - Current != ElectricCurrentUnit.Undefined && - Temperature != TemperatureUnit.Undefined && - Amount != AmountOfSubstanceUnit.Undefined && - LuminousIntensity != LuminousIntensityUnit.Undefined; + Mass != MassUnit.Undefined && + Time != DurationUnit.Undefined && + Current != ElectricCurrentUnit.Undefined && + Temperature != TemperatureUnit.Undefined && + Amount != AmountOfSubstanceUnit.Undefined && + LuminousIntensity != LuminousIntensityUnit.Undefined; } - /// - public override bool Equals(object obj) - { - if(obj is null || !(obj is BaseUnits)) - return false; + /// + /// Represents BaseUnits that have not been defined. + /// + public static BaseUnits Undefined { get; } = new BaseUnits(); - return Equals((BaseUnits)obj); - } + /// + /// Gets the length unit (L). + /// + public LengthUnit Length { get; } + + /// + /// Gets the mass unit (M). + /// + public MassUnit Mass { get; } + + /// + /// Gets the time unit (T). + /// + public DurationUnit Time { get; } + + /// + /// Gets the electric current unit (I). + /// + public ElectricCurrentUnit Current { get; } + + /// + /// Gets the temperature unit (Θ). + /// + public TemperatureUnit Temperature { get; } + + /// + /// Gets the amount of substance unit (N). + /// + public AmountOfSubstanceUnit Amount { get; } + + /// + /// Gets the luminous intensity unit (J). + /// + public LuminousIntensityUnit LuminousIntensity { get; } + + /// + /// Gets whether or not all of the base units are defined. + /// + public bool IsFullyDefined { get; } /// - /// Checks if all of the base units are equal to another instance's. + /// Checks if all of the base units are equal to another instance's. /// /// The other instance to check if equal to. /// True if equal, otherwise false. public bool Equals(BaseUnits other) { - if(other is null) + if (other is null) + { return false; + } return Length == other.Length && - Mass == other.Mass && - Time == other.Time && - Current == other.Current && - Temperature == other.Temperature && - Amount == other.Amount && - LuminousIntensity == other.LuminousIntensity; + Mass == other.Mass && + Time == other.Time && + Current == other.Current && + Temperature == other.Temperature && + Amount == other.Amount && + LuminousIntensity == other.LuminousIntensity; + } + + /// + public override bool Equals(object obj) + { + if (obj is null || !(obj is BaseUnits)) + { + return false; + } + + return Equals((BaseUnits) obj); } /// - /// Checks if the base units are a subset of another. Undefined base units are ignored. - /// If all base united are undefined (equal to ), - /// IsSubsetOf will return true only if other is also equal to . + /// Checks if the base units are a subset of another. Undefined base units are ignored. + /// If all base united are undefined (equal to ), + /// IsSubsetOf will return true only if other is also equal to . /// - /// The other to compare to. + /// The other to compare to. /// True if the base units are a subset of other, otherwise false. public bool IsSubsetOf(BaseUnits other) { - if(other is null) + if (other is null) + { return false; + } // If all base units are undefined, can only be a subset of another where all base units are undefined. - if(Equals(Undefined)) + if (Equals(Undefined)) + { return other.Equals(Undefined); + } return (Length == LengthUnit.Undefined || Length == other.Length) && - (Mass == MassUnit.Undefined || Mass == other.Mass) && - (Time == DurationUnit.Undefined || Time == other.Time) && - (Current == ElectricCurrentUnit.Undefined || Current == other.Current) && - (Temperature == TemperatureUnit.Undefined || Temperature == other.Temperature) && - (Amount == AmountOfSubstanceUnit.Undefined || Amount == other.Amount) && - (LuminousIntensity == LuminousIntensityUnit.Undefined || LuminousIntensity == other.LuminousIntensity); + (Mass == MassUnit.Undefined || Mass == other.Mass) && + (Time == DurationUnit.Undefined || Time == other.Time) && + (Current == ElectricCurrentUnit.Undefined || Current == other.Current) && + (Temperature == TemperatureUnit.Undefined || Temperature == other.Temperature) && + (Amount == AmountOfSubstanceUnit.Undefined || Amount == other.Amount) && + (LuminousIntensity == LuminousIntensityUnit.Undefined || LuminousIntensity == other.LuminousIntensity); } /// public override int GetHashCode() { - return new {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}.GetHashCode(); + return new + { + Length, + Mass, + Time, + Current, + Temperature, + Amount, + LuminousIntensity + }.GetHashCode(); } /// - /// Checks if this instance is equal to another. + /// Checks if this instance is equal to another. /// /// The left instance. /// The right instance. /// True if equal, otherwise false. - /// + /// public static bool operator ==(BaseUnits left, BaseUnits right) { return left is null ? right is null : left.Equals(right); } /// - /// Checks if this instance is not equal to another. + /// Checks if this instance is not equal to another. /// /// The left instance. /// The right instance. /// True if not equal, otherwise false. - /// + /// public static bool operator !=(BaseUnits left, BaseUnits right) { return !(left == right); @@ -154,45 +211,5 @@ public override string ToString() return sb.ToString(); } - - /// - /// Gets the length unit (L). - /// - public LengthUnit Length { get; } - - /// - /// Gets the mass unit (M). - /// - public MassUnit Mass{ get; } - - /// - /// Gets the time unit (T). - /// - public DurationUnit Time{ get; } - - /// - /// Gets the electric current unit (I). - /// - public ElectricCurrentUnit Current{ get; } - - /// - /// Gets the temperature unit (Θ). - /// - public TemperatureUnit Temperature{ get; } - - /// - /// Gets the amount of substance unit (N). - /// - public AmountOfSubstanceUnit Amount{ get; } - - /// - /// Gets the luminous intensity unit (J). - /// - public LuminousIntensityUnit LuminousIntensity{ get; } - - /// - /// Gets whether or not all of the base units are defined. - /// - public bool IsFullyDefined { get; } } } diff --git a/UnitsNet/Comparison.cs b/UnitsNet/Comparison.cs index 575707e6b5..a1175dd1cc 100644 --- a/UnitsNet/Comparison.cs +++ b/UnitsNet/Comparison.cs @@ -52,7 +52,9 @@ public static class Comparison public static bool Equals(double referenceValue, double otherValue, double tolerance, ComparisonType comparisonType) { if (tolerance < 0) + { throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + } switch (comparisonType) { @@ -89,7 +91,9 @@ public static bool Equals(double referenceValue, double otherValue, double toler public static bool EqualsRelative(double referenceValue, double otherValue, double tolerance) { if (tolerance < 0) + { throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + } var maxVariation = Math.Abs(referenceValue * tolerance); return Math.Abs(referenceValue - otherValue) <= maxVariation; @@ -117,7 +121,9 @@ public static bool EqualsRelative(double referenceValue, double otherValue, doub public static bool EqualsAbsolute(double value1, double value2, double tolerance) { if (tolerance < 0) + { throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); + } return Math.Abs(value1 - value2) <= tolerance; } diff --git a/UnitsNet/ComparisonType.cs b/UnitsNet/ComparisonType.cs index 18f76cfdd3..152ef294d7 100644 --- a/UnitsNet/ComparisonType.cs +++ b/UnitsNet/ComparisonType.cs @@ -4,17 +4,17 @@ namespace UnitsNet { /// - /// Specifies if the comparison between numbers is absolute or relative. + /// Specifies if the comparison between numbers is absolute or relative. /// public enum ComparisonType { /// - /// Error margin in relative size to a reference value. + /// Error margin in relative size to a reference value. /// Relative, /// - /// Error margin as absolute size. + /// Error margin as absolute size. /// Absolute } diff --git a/UnitsNet/CustomCode/GlobalConfiguration.cs b/UnitsNet/CustomCode/GlobalConfiguration.cs index 746e98dc65..f08345870d 100644 --- a/UnitsNet/CustomCode/GlobalConfiguration.cs +++ b/UnitsNet/CustomCode/GlobalConfiguration.cs @@ -16,7 +16,7 @@ namespace UnitsNet public static class GlobalConfiguration { /// - /// Wrapper for . + /// Wrapper for . /// [Obsolete("Manipulate Thread.CurrentThread.CurrentUICulture instead, this property will be removed.")] public static IFormatProvider DefaultCulture diff --git a/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs b/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs index 75a2eba9cf..4df4832f72 100644 --- a/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs @@ -1,16 +1,18 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using UnitsNet.Units; + namespace UnitsNet { public partial struct Acceleration { /// - /// Multiply and to get . + /// Multiply and to get . /// public static SpecificWeight operator *(Acceleration acceleration, Density density) { - return new SpecificWeight(acceleration.MetersPerSecondSquared * density.KilogramsPerCubicMeter, UnitsNet.Units.SpecificWeightUnit.NewtonPerCubicMeter); + return new SpecificWeight(acceleration.MetersPerSecondSquared * density.KilogramsPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter); } } } diff --git a/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs b/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs index 30693f48eb..2689919638 100644 --- a/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs @@ -10,22 +10,27 @@ namespace UnitsNet public partial struct AmountOfSubstance { /// - /// The Avogadro constant is the number of constituent particles, usually molecules, - /// atoms or ions that are contained in the amount of substance given by one mole. It is the proportionality factor that relates - /// the molar mass of a substance to the mass of a sample, is designated with the symbol NA or L[1], and has the value + /// The Avogadro constant is the number of constituent particles, usually molecules, + /// atoms or ions that are contained in the amount of substance given by one mole. It is the proportionality factor + /// that relates + /// the molar mass of a substance to the mass of a sample, is designated with the symbol NA or L[1], and has the value /// 6.02214076e23 mol−1 in the International System of Units (SI). /// /// - /// Pending revisions in the base set of SI units necessitated redefinitions of the concepts of chemical quantity. The Avogadro number, - /// and its definition, was deprecated in favor of the Avogadro constant and its definition. Based on measurements made through the - /// middle of 2017 which calculated a value for the Avogadro constant of NA = 6.022140758(62)×1023 mol−1, the redefinition of SI units + /// Pending revisions in the base set of SI units necessitated redefinitions of the concepts of chemical quantity. The + /// Avogadro number, + /// and its definition, was deprecated in favor of the Avogadro constant and its definition. Based on measurements made + /// through the + /// middle of 2017 which calculated a value for the Avogadro constant of NA = 6.022140758(62)×1023 mol−1, the + /// redefinition of SI units /// is planned to take effect on 20 May 2019. The value of the constant will be fixed to exactly 6.02214076×1023 mol−1. /// See here: https://www.bipm.org/utils/common/pdf/CGPM-2018/26th-CGPM-Resolutions.pdf /// public static double AvogadroConstant { get; } = 6.02214076e23; /// - /// Calculates the number of particles (atoms or molecules) in this amount of substance using the . + /// Calculates the number of particles (atoms or molecules) in this amount of substance using the + /// . /// /// The number of particles (atoms or molecules) in this amount of substance. public double NumberOfParticles() @@ -40,7 +45,7 @@ public static AmountOfSubstance FromMass(Mass mass, MolarMass molarMass) { return mass / molarMass; } - + /// Get from for a given . public static Mass operator *(AmountOfSubstance amountOfSubstance, MolarMass molarMass) { @@ -64,6 +69,5 @@ public static AmountOfSubstance FromMass(Mass mass, MolarMass molarMass) { return Volume.FromCubicMeters(amountOfSubstance.Moles / molarity.MolesPerCubicMeter); } - } } diff --git a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs index cc0a3cfcdf..b494ce8e4a 100644 --- a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs @@ -19,9 +19,11 @@ public AmplitudeRatio(ElectricPotential voltage) : this() { if (voltage.Volts <= 0) + { throw new ArgumentOutOfRangeException( nameof(voltage), "The base-10 logarithm of a number ≤ 0 is undefined. Voltage must be greater than 0 V."); + } // E(dBV) = 20*log10(value(V)/reference(V)) _value = 20 * Math.Log10(voltage.Volts / 1); @@ -40,7 +42,7 @@ public AmplitudeRatio(ElectricPotential voltage) public ElectricPotential ToElectricPotential() { // E(V) = 1V * 10^(E(dBV)/20) - return ElectricPotential.FromVolts( Math.Pow( 10, DecibelVolts / 20 ) ); + return ElectricPotential.FromVolts(Math.Pow(10, DecibelVolts / 20)); } /// @@ -48,10 +50,10 @@ public ElectricPotential ToElectricPotential() /// /// The input impedance of the load. This is usually 50, 75 or 600 ohms. /// http://www.maximintegrated.com/en/app-notes/index.mvp/id/808 - public PowerRatio ToPowerRatio( ElectricResistance impedance ) + public PowerRatio ToPowerRatio(ElectricResistance impedance) { // P(dBW) = E(dBV) - 10*log10(Z(Ω)/1) - return PowerRatio.FromDecibelWatts( DecibelVolts - 10 * Math.Log10( impedance.Ohms / 1 ) ); + return PowerRatio.FromDecibelWatts(DecibelVolts - 10 * Math.Log10(impedance.Ohms / 1)); } #region Static Methods diff --git a/UnitsNet/CustomCode/Quantities/Angle.extra.cs b/UnitsNet/CustomCode/Quantities/Angle.extra.cs index 59318915c4..7b64e742b1 100644 --- a/UnitsNet/CustomCode/Quantities/Angle.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Angle.extra.cs @@ -7,7 +7,7 @@ namespace UnitsNet { public partial struct Angle { - /// Get from delta over time delta. + /// Get from delta over time delta. public static RotationalSpeed operator /(Angle angle, TimeSpan timeSpan) { return RotationalSpeed.FromRadiansPerSecond(angle.Radians / timeSpan.TotalSeconds); diff --git a/UnitsNet/CustomCode/Quantities/Area.extra.cs b/UnitsNet/CustomCode/Quantities/Area.extra.cs index a4c005015c..6bcb0696fa 100644 --- a/UnitsNet/CustomCode/Quantities/Area.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Area.extra.cs @@ -24,19 +24,19 @@ public static Area FromCircleRadius(Length radius) #endregion - /// Get from divided by . + /// Get from divided by . public static Length operator /(Area area, Length length) { return Length.FromMeters(area.SquareMeters / length.Meters); } - /// Get from times . + /// Get from times . public static MassFlow operator *(Area area, MassFlux massFlux) { return MassFlow.FromGramsPerSecond(area.SquareMeters * massFlux.GramsPerSecondPerSquareMeter); } - /// Get from times . + /// Get from times . public static VolumeFlow operator *(Area area, Speed speed) { return VolumeFlow.FromCubicMetersPerSecond(area.SquareMeters * speed.MetersPerSecond); diff --git a/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs b/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs index 6afa77213e..65545160af 100644 --- a/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs @@ -1,13 +1,11 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using System; - namespace UnitsNet { public partial struct AreaMomentOfInertia { - /// Get from divided by . + /// Get from divided by . public static Volume operator /(AreaMomentOfInertia areaMomentOfInertia, Length length) { return Volume.FromCubicMeters(areaMomentOfInertia.MetersToTheFourth / length.Meters); diff --git a/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs b/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs index 5bd29a877a..a8f3b6479f 100644 --- a/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs +++ b/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs @@ -5,22 +5,25 @@ namespace UnitsNet { public partial struct BrakeSpecificFuelConsumption { - /// Get from times . + /// Get from times . public static MassFlow operator *(BrakeSpecificFuelConsumption bsfc, Power power) { - return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule*power.Watts); + return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule * power.Watts); } - /// Get from divided by . + /// + /// Get from divided by + /// . + /// public static SpecificEnergy operator /(double value, BrakeSpecificFuelConsumption bsfc) { - return SpecificEnergy.FromJoulesPerKilogram(value/bsfc.KilogramsPerJoule); + return SpecificEnergy.FromJoulesPerKilogram(value / bsfc.KilogramsPerJoule); } - /// Get constant from times . + /// Get constant from times . public static double operator *(BrakeSpecificFuelConsumption bsfc, SpecificEnergy specificEnergy) { - return specificEnergy.JoulesPerKilogram*bsfc.KilogramsPerJoule; + return specificEnergy.JoulesPerKilogram * bsfc.KilogramsPerJoule; } } } diff --git a/UnitsNet/CustomCode/Quantities/Density.extra.cs b/UnitsNet/CustomCode/Quantities/Density.extra.cs index e569cefac5..ad4514df59 100644 --- a/UnitsNet/CustomCode/Quantities/Density.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Density.extra.cs @@ -12,7 +12,7 @@ public partial struct Density /// Gets from this . /// /// - /// + /// [Obsolete("This method is deprecated in favor of MassConcentration.ToMolarity(MolarMass).")] public Molarity ToMolarity(Mass molecularWeight) { @@ -24,7 +24,7 @@ public Molarity ToMolarity(Mass molecularWeight) /// /// Get from . /// - /// + /// [Obsolete("This method is deprecated in favor of MassConcentration.FromMolarity(Molarity, MolarMass).")] public static Density FromMolarity(Molarity molarity, Mass molecularWeight) { @@ -33,38 +33,38 @@ public static Density FromMolarity(Molarity molarity, Mass molecularWeight) #endregion - /// Get from times . + /// Get from times . public static Mass operator *(Density density, Volume volume) { return Mass.FromKilograms(density.KilogramsPerCubicMeter * volume.CubicMeters); } - /// Get from times . + /// Get from times . public static Mass operator *(Volume volume, Density density) { return Mass.FromKilograms(density.KilogramsPerCubicMeter * volume.CubicMeters); } - /// Get from times . + /// Get from times . public static DynamicViscosity operator *(Density density, KinematicViscosity kinematicViscosity) { return DynamicViscosity.FromNewtonSecondsPerMeterSquared(kinematicViscosity.SquareMetersPerSecond * density.KilogramsPerCubicMeter); } - /// Get times . + /// Get times . public static MassFlux operator *(Density density, Speed speed) { return MassFlux.FromKilogramsPerSecondPerSquareMeter(density.KilogramsPerCubicMeter * speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static SpecificWeight operator *(Density density, Acceleration acceleration) { return new SpecificWeight(density.KilogramsPerCubicMeter * acceleration.MetersPerSecondSquared, SpecificWeightUnit.NewtonPerCubicMeter); } - /// Get from divided by . - /// + /// Get from divided by . + /// [Obsolete("This operator is deprecated in favor of MassConcentration.op_Division(MassConcentration, MolarMass).")] public static Molarity operator /(Density density, Mass molecularWeight) { diff --git a/UnitsNet/CustomCode/Quantities/Duration.extra.cs b/UnitsNet/CustomCode/Quantities/Duration.extra.cs index 61501525a0..c849e9fde9 100644 --- a/UnitsNet/CustomCode/Quantities/Duration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Duration.extra.cs @@ -14,85 +14,88 @@ public partial struct Duration /// The TimeSpan with the same time as the duration public TimeSpan ToTimeSpan() { - if( Seconds > TimeSpan.MaxValue.TotalSeconds || - Seconds < TimeSpan.MinValue.TotalSeconds ) - throw new ArgumentOutOfRangeException( nameof( Duration ), "The duration is too large or small to fit in a TimeSpan" ); - return TimeSpan.FromSeconds( Seconds ); + if (Seconds > TimeSpan.MaxValue.TotalSeconds || + Seconds < TimeSpan.MinValue.TotalSeconds) + { + throw new ArgumentOutOfRangeException(nameof(Duration), "The duration is too large or small to fit in a TimeSpan"); + } + + return TimeSpan.FromSeconds(Seconds); } - /// Get from plus . + /// Get from plus . public static DateTime operator +(DateTime time, Duration duration) { return time.AddSeconds(duration.Seconds); } - /// Get from minus . + /// Get from minus . public static DateTime operator -(DateTime time, Duration duration) { return time.AddSeconds(-duration.Seconds); } - /// Explicitly cast to . + /// Explicitly cast to . public static explicit operator TimeSpan(Duration duration) { return duration.ToTimeSpan(); } - /// Explicitly cast to . + /// Explicitly cast to . public static explicit operator Duration(TimeSpan duration) { return FromSeconds(duration.TotalSeconds); } - /// True if is less than . + /// True if is less than . public static bool operator <(Duration duration, TimeSpan timeSpan) { return duration.Seconds < timeSpan.TotalSeconds; } - /// True if is greater than . + /// True if is greater than . public static bool operator >(Duration duration, TimeSpan timeSpan) { return duration.Seconds > timeSpan.TotalSeconds; } - /// True if is less than or equal to . + /// True if is less than or equal to . public static bool operator <=(Duration duration, TimeSpan timeSpan) { return duration.Seconds <= timeSpan.TotalSeconds; } - /// True if is greater than or equal to . + /// True if is greater than or equal to . public static bool operator >=(Duration duration, TimeSpan timeSpan) { return duration.Seconds >= timeSpan.TotalSeconds; } - /// True if is less than . + /// True if is less than . public static bool operator <(TimeSpan timeSpan, Duration duration) { return timeSpan.TotalSeconds < duration.Seconds; } - /// True if is greater than . + /// True if is greater than . public static bool operator >(TimeSpan timeSpan, Duration duration) { return timeSpan.TotalSeconds > duration.Seconds; } - /// True if is less than or equal to . + /// True if is less than or equal to . public static bool operator <=(TimeSpan timeSpan, Duration duration) { return timeSpan.TotalSeconds <= duration.Seconds; } - /// True if is greater than or equal to . + /// True if is greater than or equal to . public static bool operator >=(TimeSpan timeSpan, Duration duration) { return timeSpan.TotalSeconds >= duration.Seconds; } - /// Get from times . + /// Get from times . public static Volume operator *(Duration duration, VolumeFlow volumeFlow) { return Volume.FromCubicMeters(volumeFlow.CubicMetersPerSecond * duration.Seconds); diff --git a/UnitsNet/CustomCode/Quantities/DynamicViscosity.extra.cs b/UnitsNet/CustomCode/Quantities/DynamicViscosity.extra.cs index e99348a111..6c11f685e2 100644 --- a/UnitsNet/CustomCode/Quantities/DynamicViscosity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/DynamicViscosity.extra.cs @@ -5,7 +5,7 @@ namespace UnitsNet { public partial struct DynamicViscosity { - /// Get from divided by . + /// Get from divided by . public static KinematicViscosity operator /(DynamicViscosity dynamicViscosity, Density density) { return KinematicViscosity.FromSquareMetersPerSecond(dynamicViscosity.NewtonSecondsPerMeterSquared / density.KilogramsPerCubicMeter); diff --git a/UnitsNet/CustomCode/Quantities/ElectricCurrent.extra.cs b/UnitsNet/CustomCode/Quantities/ElectricCurrent.extra.cs index 261edea0c2..dddb95a2e6 100644 --- a/UnitsNet/CustomCode/Quantities/ElectricCurrent.extra.cs +++ b/UnitsNet/CustomCode/Quantities/ElectricCurrent.extra.cs @@ -5,7 +5,10 @@ namespace UnitsNet { public partial struct ElectricCurrent { - /// Get from multiplied by . + /// + /// Get from multiplied by + /// . + /// /// Ohm's law implementation public static ElectricPotential operator *(ElectricCurrent current, ElectricResistance resistance) { diff --git a/UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs b/UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs index 78e15c5fd8..c0ef93827a 100644 --- a/UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs +++ b/UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs @@ -6,7 +6,8 @@ namespace UnitsNet public partial struct ElectricPotential { /// - /// Gets an in decibels (dB) relative to 1 volt RMS from this . + /// Gets an in decibels (dB) relative to 1 volt RMS from this + /// . /// /// /// Provides a nicer syntax for converting a voltage to an amplitude ratio (relative to 1 volt RMS). @@ -19,14 +20,20 @@ public AmplitudeRatio ToAmplitudeRatio() return AmplitudeRatio.FromElectricPotential(this); } - /// Get from divided by . + /// + /// Get from divided by + /// . + /// /// Ohm's law implementation public static ElectricResistance operator /(ElectricPotential potential, ElectricCurrent current) { return ElectricResistance.FromOhms(potential.Volts / current.Amperes); } - /// Get from divided by . + /// + /// Get from divided by + /// . + /// /// Ohm's law implementation public static ElectricCurrent operator /(ElectricPotential potential, ElectricResistance resistance) { diff --git a/UnitsNet/CustomCode/Quantities/ElectricResistance.extra.cs b/UnitsNet/CustomCode/Quantities/ElectricResistance.extra.cs index 95d103d89e..4f64e6ec9b 100644 --- a/UnitsNet/CustomCode/Quantities/ElectricResistance.extra.cs +++ b/UnitsNet/CustomCode/Quantities/ElectricResistance.extra.cs @@ -5,7 +5,10 @@ namespace UnitsNet { public partial struct ElectricResistance { - /// Get from multiplied by . + /// + /// Get from multiplied by + /// . + /// /// Ohm's law implementation public static ElectricPotential operator *(ElectricResistance resistance, ElectricCurrent current) { diff --git a/UnitsNet/CustomCode/Quantities/Force.extra.cs b/UnitsNet/CustomCode/Quantities/Force.extra.cs index 1d9881edff..372caccc06 100644 --- a/UnitsNet/CustomCode/Quantities/Force.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Force.extra.cs @@ -7,50 +7,50 @@ namespace UnitsNet { public partial struct Force { - /// Get from divided by . + /// Get from divided by . public static Force FromPressureByArea(Pressure p, Area area) { - double newtons = p.Pascals * area.SquareMeters; + var newtons = p.Pascals * area.SquareMeters; return new Force(newtons, ForceUnit.Newton); } - /// Get from times . + /// Get from times . public static Force FromMassByAcceleration(Mass mass, Acceleration acceleration) { return new Force(mass.Kilograms * acceleration.MetersPerSecondSquared, ForceUnit.Newton); } - /// Get from times . + /// Get from times . public static Power operator *(Force force, Speed speed) { return Power.FromWatts(force.Newtons * speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static Power operator *(Speed speed, Force force) { return Power.FromWatts(force.Newtons * speed.MetersPerSecond); } - /// Get from divided by . + /// Get from divided by . public static Acceleration operator /(Force force, Mass mass) { return Acceleration.FromMetersPerSecondSquared(force.Newtons / mass.Kilograms); } - /// Get from divided by . + /// Get from divided by . public static Mass operator /(Force force, Acceleration acceleration) { return Mass.FromKilograms(force.Newtons / acceleration.MetersPerSecondSquared); } - /// Get from divided by . + /// Get from divided by . public static Pressure operator /(Force force, Area area) { return Pressure.FromPascals(force.Newtons / area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static ForcePerLength operator /(Force force, Length length) { return ForcePerLength.FromNewtonsPerMeter(force.Newtons / length.Meters); diff --git a/UnitsNet/CustomCode/Quantities/ForcePerLength.extra.cs b/UnitsNet/CustomCode/Quantities/ForcePerLength.extra.cs index 813190866f..bb9e870230 100644 --- a/UnitsNet/CustomCode/Quantities/ForcePerLength.extra.cs +++ b/UnitsNet/CustomCode/Quantities/ForcePerLength.extra.cs @@ -5,19 +5,19 @@ namespace UnitsNet { public partial struct ForcePerLength { - /// Get from divided by . + /// Get from divided by . public static Force operator *(ForcePerLength forcePerLength, Length length) { return Force.FromNewtons(forcePerLength.NewtonsPerMeter * length.Meters); } - /// Get from divided by . + /// Get from divided by . public static Length operator /(Force force, ForcePerLength forcePerLength) { return Length.FromMeters(force.Newtons / forcePerLength.NewtonsPerMeter); } - /// Get from divided by . + /// Get from divided by . public static Pressure operator /(ForcePerLength forcePerLength, Length length) { return Pressure.FromNewtonsPerSquareMeter(forcePerLength.NewtonsPerMeter / length.Meters); diff --git a/UnitsNet/CustomCode/Quantities/HeatFlux.extra.cs b/UnitsNet/CustomCode/Quantities/HeatFlux.extra.cs index 395661fb1f..940d38dcce 100644 --- a/UnitsNet/CustomCode/Quantities/HeatFlux.extra.cs +++ b/UnitsNet/CustomCode/Quantities/HeatFlux.extra.cs @@ -5,7 +5,7 @@ namespace UnitsNet { public partial struct HeatFlux { - /// Get from times . + /// Get from times . public static Power operator *(HeatFlux heatFlux, Area area) { return Power.FromWatts(heatFlux.WattsPerSquareMeter * area.SquareMeters); diff --git a/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs b/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs index f43b75534c..56677fb252 100644 --- a/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs @@ -7,37 +7,37 @@ namespace UnitsNet { public partial struct KinematicViscosity { - /// Get from divided by . + /// Get from divided by . public static Speed operator /(KinematicViscosity kinematicViscosity, Length length) { return Speed.FromMetersPerSecond(kinematicViscosity.SquareMetersPerSecond / length.Meters); } - /// Get from times . + /// Get from times . public static Area operator *(KinematicViscosity kinematicViscosity, TimeSpan timeSpan) { return Area.FromSquareMeters(kinematicViscosity.SquareMetersPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Area operator *(TimeSpan timeSpan, KinematicViscosity kinematicViscosity) { return Area.FromSquareMeters(kinematicViscosity.SquareMetersPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Area operator *(KinematicViscosity kinematicViscosity, Duration duration) { return Area.FromSquareMeters(kinematicViscosity.SquareMetersPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static Area operator *(Duration duration, KinematicViscosity kinematicViscosity) { return Area.FromSquareMeters(kinematicViscosity.SquareMetersPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static DynamicViscosity operator *(KinematicViscosity kinematicViscosity, Density density) { return DynamicViscosity.FromNewtonSecondsPerMeterSquared(kinematicViscosity.SquareMetersPerSecond * density.KilogramsPerCubicMeter); diff --git a/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs b/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs index 6f675602e0..8d15572028 100644 --- a/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs +++ b/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs @@ -5,16 +5,16 @@ namespace UnitsNet { public partial struct LapseRate { - /// Get from divided by . + /// Get from divided by . public static Length operator /(TemperatureDelta left, LapseRate right) { return Length.FromKilometers(left.Kelvins / right.DegreesCelciusPerKilometer); } - /// Get from times . + /// Get from times . public static TemperatureDelta operator *(Length left, LapseRate right) => right * left; - /// Get from times . + /// Get from times . public static TemperatureDelta operator *(LapseRate left, Length right) { return TemperatureDelta.FromDegreesCelsius(left.DegreesCelciusPerKilometer * right.Kilometers); diff --git a/UnitsNet/CustomCode/Quantities/Length.extra.cs b/UnitsNet/CustomCode/Quantities/Length.extra.cs index 97f64c4805..fe240f8ea7 100644 --- a/UnitsNet/CustomCode/Quantities/Length.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Length.extra.cs @@ -34,23 +34,26 @@ public FeetInches FeetInches /// public static Length FromFeetInches(double feet, double inches) { - return FromInches(InchesInOneFoot*feet + inches); + return FromInches(InchesInOneFoot * feet + inches); } /// - /// Special parsing of feet/inches strings, commonly used. - /// 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″, 2′4″, 2 ft 4 in. - /// The apostrophe can be ′ and '. - /// The double prime can be ″ and ". - /// https://en.wikipedia.org/wiki/Foot_(unit) + /// Special parsing of feet/inches strings, commonly used. + /// 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″, 2′4″, 2 ft 4 in. + /// The apostrophe can be ′ and '. + /// The double prime can be ″ and ". + /// https://en.wikipedia.org/wiki/Foot_(unit) /// /// - /// Optionally specify the culture format numbers and localize unit abbreviations. Defaults to thread's culture. + /// + /// Optionally specify the culture format numbers and localize unit abbreviations. Defaults to + /// thread's culture. + /// /// Parsed length. public static Length ParseFeetInches([NotNull] string str, IFormatProvider formatProvider = null) { if (str == null) throw new ArgumentNullException(nameof(str)); - if (!TryParseFeetInches(str, out Length result, formatProvider)) + if (!TryParseFeetInches(str, out var result, formatProvider)) { // A bit lazy, but I didn't want to duplicate this edge case implementation just to get more narrow exception descriptions. throw new FormatException("Unable to parse feet and inches. Expected format \"2' 4\"\" or \"2 ft 4 in\". Whitespace is optional."); @@ -60,15 +63,18 @@ public static Length ParseFeetInches([NotNull] string str, IFormatProvider forma } /// - /// Special parsing of feet/inches strings, commonly used. - /// 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″, 2′4″, 2 ft 4 in. - /// The apostrophe can be ′ and '. - /// The double prime can be ″ and ". - /// https://en.wikipedia.org/wiki/Foot_(unit) + /// Special parsing of feet/inches strings, commonly used. + /// 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″, 2′4″, 2 ft 4 in. + /// The apostrophe can be ′ and '. + /// The double prime can be ″ and ". + /// https://en.wikipedia.org/wiki/Foot_(unit) /// /// /// Parsed length. - /// Optionally specify the culture format numbers and localize unit abbreviations. Defaults to thread's culture. + /// + /// Optionally specify the culture format numbers and localize unit abbreviations. Defaults to + /// thread's culture. + /// public static bool TryParseFeetInches([CanBeNull] string str, out Length result, IFormatProvider formatProvider = null) { if (str == null) @@ -81,30 +87,36 @@ public static bool TryParseFeetInches([CanBeNull] string str, out Length result, // This succeeds if only feet or inches are given, not both if (TryParse(str, formatProvider, out result)) + { return true; + } var quantityParser = QuantityParser.Default; - string footRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Foot, formatProvider, matchEntireString: false); - string inchRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Inch, formatProvider, matchEntireString: false); + var footRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Foot, formatProvider, false); + var inchRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Inch, formatProvider, false); // Match entire string exactly - string pattern = $@"^(?\-?)(?{footRegex})\s?(?{inchRegex})$"; + var pattern = $@"^(?\-?)(?{footRegex})\s?(?{inchRegex})$"; var match = new Regex(pattern, RegexOptions.Singleline).Match(str); if (!match.Success) + { return false; + } var negativeSignGroup = match.Groups["negativeSign"]; var feetGroup = match.Groups["feet"]; var inchesGroup = match.Groups["inches"]; - if (TryParse(feetGroup.Value, formatProvider, out Length feet) && - TryParse(inchesGroup.Value, formatProvider, out Length inches)) + if (TryParse(feetGroup.Value, formatProvider, out var feet) && + TryParse(inchesGroup.Value, formatProvider, out var inches)) { result = feet + inches; - if(negativeSignGroup.Length > 0) + if (negativeSignGroup.Length > 0) + { result = -result; + } return true; } @@ -113,61 +125,61 @@ public static bool TryParseFeetInches([CanBeNull] string str, out Length result, return false; } - /// Get from divided by . + /// Get from divided by . public static Speed operator /(Length length, TimeSpan timeSpan) { - return Speed.FromMetersPerSecond(length.Meters/timeSpan.TotalSeconds); + return Speed.FromMetersPerSecond(length.Meters / timeSpan.TotalSeconds); } - /// Get from divided by . + /// Get from divided by . public static Speed operator /(Length length, Duration duration) { - return Speed.FromMetersPerSecond(length.Meters/duration.Seconds); + return Speed.FromMetersPerSecond(length.Meters / duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static Duration operator /(Length length, Speed speed) { - return Duration.FromSeconds(length.Meters/speed.MetersPerSecond); + return Duration.FromSeconds(length.Meters / speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static Area operator *(Length length1, Length length2) { - return Area.FromSquareMeters(length1.Meters*length2.Meters); + return Area.FromSquareMeters(length1.Meters * length2.Meters); } - /// Get from times . + /// Get from times . public static Volume operator *(Area area, Length length) { - return Volume.FromCubicMeters(area.SquareMeters*length.Meters); + return Volume.FromCubicMeters(area.SquareMeters * length.Meters); } - /// Get from times . + /// Get from times . public static Volume operator *(Length length, Area area) { - return Volume.FromCubicMeters(area.SquareMeters*length.Meters); + return Volume.FromCubicMeters(area.SquareMeters * length.Meters); } - /// Get from times . + /// Get from times . public static Torque operator *(Force force, Length length) { - return Torque.FromNewtonMeters(force.Newtons*length.Meters); + return Torque.FromNewtonMeters(force.Newtons * length.Meters); } - /// Get from times . + /// Get from times . public static Torque operator *(Length length, Force force) { - return Torque.FromNewtonMeters(force.Newtons*length.Meters); + return Torque.FromNewtonMeters(force.Newtons * length.Meters); } - /// Get from times . + /// Get from times . public static KinematicViscosity operator *(Length length, Speed speed) { - return KinematicViscosity.FromSquareMetersPerSecond(length.Meters*speed.MetersPerSecond); + return KinematicViscosity.FromSquareMetersPerSecond(length.Meters * speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static Pressure operator *(Length length, SpecificWeight specificWeight) { return new Pressure(length.Meters * specificWeight.NewtonsPerCubicMeter, PressureUnit.Pascal); @@ -175,8 +187,8 @@ public static bool TryParseFeetInches([CanBeNull] string str, out Length result, } /// - /// Representation of feet and inches, used to preserve the original values when constructing by - /// and later output them unaltered with . + /// Representation of feet and inches, used to preserve the original values when constructing by + /// and later output them unaltered with . /// public sealed class FeetInches { @@ -199,7 +211,7 @@ public FeetInches(double feet, double inches) /// public double Inches { get; } - /// + /// public override string ToString() { return ToString(null); @@ -211,7 +223,7 @@ public override string ToString() /// Length.FromFeetInches(3,2).FeetInches.ToString() outputs: "3 ft 2 in" /// /// Optional culture to format number and localize unit abbreviations. - /// If null, defaults to . + /// If null, defaults to . /// public string ToString([CanBeNull] IFormatProvider cultureInfo) { diff --git a/UnitsNet/CustomCode/Quantities/Level.extra.cs b/UnitsNet/CustomCode/Quantities/Level.extra.cs index a7b1a82825..29645ffe79 100644 --- a/UnitsNet/CustomCode/Quantities/Level.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Level.extra.cs @@ -17,17 +17,22 @@ public partial struct Level public Level(double quantity, double reference) : this() { - string errorMessage = + var errorMessage = $"The base-10 logarithm of a number ≤ 0 is undefined ({quantity}/{reference})."; // ReSharper disable CompareOfFloatsByEqualityOperator if (quantity == 0 || quantity < 0 && reference > 0) + { throw new ArgumentOutOfRangeException(nameof(quantity), errorMessage); + } + if (reference == 0 || quantity > 0 && reference < 0) + { throw new ArgumentOutOfRangeException(nameof(reference), errorMessage); + } // ReSharper restore CompareOfFloatsByEqualityOperator - _value = 10*Math.Log10(quantity/reference); + _value = 10 * Math.Log10(quantity / reference); _unit = LevelUnit.Decibel; } } diff --git a/UnitsNet/CustomCode/Quantities/Mass.extra.cs b/UnitsNet/CustomCode/Quantities/Mass.extra.cs index 418adf58f8..436f0e5cab 100644 --- a/UnitsNet/CustomCode/Quantities/Mass.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Mass.extra.cs @@ -2,8 +2,8 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using System.Threading; using System.Globalization; +using System.Threading; using JetBrains.Annotations; using UnitsNet.Units; @@ -11,7 +11,7 @@ namespace UnitsNet { public partial struct Mass { - /// Get from of gravity. + /// Get from of gravity. public static Mass FromGravitationalForce(Force f) { return new Mass(f.KilogramsForce, MassUnit.Kilogram); @@ -44,28 +44,28 @@ public StonePounds StonePounds /// public static Mass FromStonePounds(double stone, double pounds) { - return FromPounds(StonesInOnePound*stone + pounds); + return FromPounds(StonesInOnePound * stone + pounds); } - /// Get from divided by . + /// Get from divided by . public static MassFlow operator /(Mass mass, TimeSpan timeSpan) { - return MassFlow.FromKilogramsPerSecond(mass.Kilograms/timeSpan.TotalSeconds); + return MassFlow.FromKilogramsPerSecond(mass.Kilograms / timeSpan.TotalSeconds); } - /// Get from divided by . + /// Get from divided by . public static MassFlow operator /(Mass mass, Duration duration) { - return MassFlow.FromKilogramsPerSecond(mass.Kilograms/duration.Seconds); + return MassFlow.FromKilogramsPerSecond(mass.Kilograms / duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static Density operator /(Mass mass, Volume volume) { - return Density.FromKilogramsPerCubicMeter(mass.Kilograms/volume.CubicMeters); + return Density.FromKilogramsPerCubicMeter(mass.Kilograms / volume.CubicMeters); } - /// Get from divided by . + /// Get from divided by . public static Volume operator /(Mass mass, Density density) { return Volume.FromCubicMeters(mass.Kilograms / density.KilogramsPerCubicMeter); @@ -77,22 +77,22 @@ public static Mass FromStonePounds(double stone, double pounds) return AmountOfSubstance.FromMoles(mass.Kilograms / molarMass.KilogramsPerMole); } - /// Get from times . + /// Get from times . public static Force operator *(Mass mass, Acceleration acceleration) { - return Force.FromNewtons(mass.Kilograms*acceleration.MetersPerSecondSquared); + return Force.FromNewtons(mass.Kilograms * acceleration.MetersPerSecondSquared); } - /// Get from times . + /// Get from times . public static Force operator *(Acceleration acceleration, Mass mass) { - return Force.FromNewtons(mass.Kilograms*acceleration.MetersPerSecondSquared); + return Force.FromNewtons(mass.Kilograms * acceleration.MetersPerSecondSquared); } } /// - /// Representation of stone and pounds, used to preserve the original values when constructing by - /// and later output them unaltered with . + /// Representation of stone and pounds, used to preserve the original values when constructing by + /// and later output them unaltered with . /// public sealed class StonePounds { @@ -115,7 +115,7 @@ public StonePounds(double stone, double pounds) /// public double Pounds { get; } - /// + /// public override string ToString() { return ToString(null); @@ -127,7 +127,7 @@ public override string ToString() /// Mass.FromStonePounds(3,2).StonePounds.ToString() outputs: "3 st 2 lb" /// /// Optional culture to format number and localize unit abbreviations. - /// If null, defaults to . + /// If null, defaults to . /// public string ToString([CanBeNull] IFormatProvider cultureInfo) { diff --git a/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs b/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs index edce6c4ee2..c063162ec9 100644 --- a/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs @@ -1,14 +1,13 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using UnitsNet.Units; - namespace UnitsNet { public partial struct MassConcentration { /// - /// Get from this using the known component . + /// Get from this using the known component + /// . /// /// public Molarity ToMolarity(MolarMass molecularWeight) @@ -17,7 +16,8 @@ public Molarity ToMolarity(MolarMass molecularWeight) } /// - /// Get from this using the known component . + /// Get from this using the known component + /// . /// /// /// @@ -48,7 +48,7 @@ public static MassConcentration FromVolumeConcentration(VolumeConcentration volu #endregion #region Operators - + /// Get from times . public static Mass operator *(MassConcentration density, Volume volume) { @@ -60,20 +60,25 @@ public static MassConcentration FromVolumeConcentration(VolumeConcentration volu { return Mass.FromKilograms(density.KilogramsPerCubicMeter * volume.CubicMeters); } - - /// Get from divided by the component's . + + /// + /// Get from divided by the component's + /// . + /// public static Molarity operator /(MassConcentration massConcentration, MolarMass componentMass) { return Molarity.FromMolesPerCubicMeter(massConcentration.GramsPerCubicMeter / componentMass.GramsPerMole); } - /// Get from divided by the component's . + /// + /// Get from divided by the component's + /// . + /// public static VolumeConcentration operator /(MassConcentration massConcentration, Density componentDensity) { return VolumeConcentration.FromDecimalFractions(massConcentration.KilogramsPerCubicMeter / componentDensity.KilogramsPerCubicMeter); } #endregion - } } diff --git a/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs b/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs index e60c5c75d8..aa1233fd72 100644 --- a/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs @@ -7,67 +7,67 @@ namespace UnitsNet { public partial struct MassFlow { - /// Get from times . + /// Get from times . public static Mass operator *(MassFlow massFlow, TimeSpan time) { return Mass.FromKilograms(massFlow.KilogramsPerSecond * time.TotalSeconds); } - /// Get from times . + /// Get from times . public static Mass operator *(TimeSpan time, MassFlow massFlow) { return Mass.FromKilograms(massFlow.KilogramsPerSecond * time.TotalSeconds); } - /// Get from times . + /// Get from times . public static Mass operator *(MassFlow massFlow, Duration duration) { return Mass.FromKilograms(massFlow.KilogramsPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static Mass operator *(Duration duration, MassFlow massFlow) { return Mass.FromKilograms(massFlow.KilogramsPerSecond * duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static Power operator /(MassFlow massFlow, BrakeSpecificFuelConsumption bsfc) { return Power.FromWatts(massFlow.KilogramsPerSecond / bsfc.KilogramsPerJoule); } - /// Get from divided by . + /// Get from divided by . public static BrakeSpecificFuelConsumption operator /(MassFlow massFlow, Power power) { return BrakeSpecificFuelConsumption.FromKilogramsPerJoule(massFlow.KilogramsPerSecond / power.Watts); } - /// Get from times . + /// Get from times . public static Power operator *(MassFlow massFlow, SpecificEnergy specificEnergy) { return Power.FromWatts(massFlow.KilogramsPerSecond * specificEnergy.JoulesPerKilogram); } - /// Get from divided by . + /// Get from divided by . public static MassFlux operator /(MassFlow massFlow, Area area) { return MassFlux.FromKilogramsPerSecondPerSquareMeter(massFlow.KilogramsPerSecond / area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static Area operator /(MassFlow massFlow, MassFlux massFlux) { return Area.FromSquareMeters(massFlow.KilogramsPerSecond / massFlux.KilogramsPerSecondPerSquareMeter); } - /// Get from divided by . + /// Get from divided by . public static Density operator /(MassFlow massFlow, VolumeFlow volumeFlow) { return Density.FromKilogramsPerCubicMeter(massFlow.KilogramsPerSecond / volumeFlow.CubicMetersPerSecond); } - /// Get from divided by . + /// Get from divided by . public static VolumeFlow operator /(MassFlow massFlow, Density density) { return VolumeFlow.FromCubicMetersPerSecond(massFlow.KilogramsPerSecond / density.KilogramsPerCubicMeter); diff --git a/UnitsNet/CustomCode/Quantities/MassFlux.extra.cs b/UnitsNet/CustomCode/Quantities/MassFlux.extra.cs index 654ce48a20..9ec650f5cd 100644 --- a/UnitsNet/CustomCode/Quantities/MassFlux.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassFlux.extra.cs @@ -5,19 +5,19 @@ namespace UnitsNet { public partial struct MassFlux { - /// Get from divided by . + /// Get from divided by . public static Density operator /(MassFlux massFlux, Speed speed) { return Density.FromKilogramsPerCubicMeter(massFlux.KilogramsPerSecondPerSquareMeter / speed.MetersPerSecond); } - /// Get from divided by . + /// Get from divided by . public static Speed operator /(MassFlux massFlux, Density density) { return Speed.FromMetersPerSecond(massFlux.KilogramsPerSecondPerSquareMeter / density.KilogramsPerCubicMeter); } - /// Get from times . + /// Get from times . public static MassFlow operator *(MassFlux massFlux, Area area) { return MassFlow.FromGramsPerSecond(massFlux.GramsPerSecondPerSquareMeter * area.SquareMeters); diff --git a/UnitsNet/CustomCode/Quantities/MassFraction.extra.cs b/UnitsNet/CustomCode/Quantities/MassFraction.extra.cs index c685887214..069d6ffb2b 100644 --- a/UnitsNet/CustomCode/Quantities/MassFraction.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassFraction.extra.cs @@ -1,11 +1,15 @@ -using UnitsNet.Units; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using UnitsNet.Units; namespace UnitsNet { public partial struct MassFraction { /// - /// Get the of the component by multiplying the of the mixture and this . + /// Get the of the component by multiplying the of the mixture and this + /// . /// /// The total mass of the mixture /// The actual mass of the component involved in this mixture @@ -15,7 +19,8 @@ public Mass GetComponentMass(Mass totalMass) } /// - /// Get the total of the mixture by dividing the of the component by this + /// Get the total of the mixture by dividing the of the component by this + /// /// /// The actual mass of the component involved in this mixture /// The total mass of the mixture @@ -36,22 +41,25 @@ public static MassFraction FromMasses(Mass componentMass, Mass mixtureMass) #endregion - /// Get from multiplied by a . + /// Get from multiplied by a . public static Mass operator *(MassFraction massFraction, Mass mass) { return Mass.FromKilograms(massFraction.DecimalFractions * mass.Kilograms); } - /// Get from multiplied by a . + /// Get from multiplied by a . public static Mass operator *(Mass mass, MassFraction massFraction) { return Mass.FromKilograms(massFraction.DecimalFractions * mass.Kilograms); } - /// Get the total by dividing the component by a . + + /// + /// Get the total by dividing the component by a + /// . + /// public static Mass operator /(Mass mass, MassFraction massFraction) { return Mass.FromKilograms(mass.Kilograms / massFraction.DecimalFractions); } - } } diff --git a/UnitsNet/CustomCode/Quantities/Molarity.extra.cs b/UnitsNet/CustomCode/Quantities/Molarity.extra.cs index 53af6eeb15..a64e743dac 100644 --- a/UnitsNet/CustomCode/Quantities/Molarity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Molarity.extra.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using UnitsNet.Units; namespace UnitsNet @@ -6,9 +9,9 @@ namespace UnitsNet public partial struct Molarity { /// - /// Construct from divided by . + /// Construct from divided by . /// - /// + /// [Obsolete("This constructor will be removed in favor of operator overload MassConcentration.op_Division(MassConcentration,MolarMass).")] public Molarity(Density density, Mass molecularWeight) : this() @@ -18,10 +21,10 @@ public Molarity(Density density, Mass molecularWeight) } /// - /// Get a from this . + /// Get a from this . /// /// - /// + /// [Obsolete("This method will be removed in favor of ToMassConcentration(MolarMass)")] public Density ToDensity(Mass molecularWeight) { @@ -29,16 +32,16 @@ public Density ToDensity(Mass molecularWeight) } /// - /// Get a from this . + /// Get a from this . /// /// - public MassConcentration ToMassConcentration(MolarMass molecularWeight) + public MassConcentration ToMassConcentration(MolarMass molecularWeight) { - return this * molecularWeight; + return this * molecularWeight; } /// - /// Get a from this . + /// Get a from this . /// /// /// @@ -50,7 +53,7 @@ public VolumeConcentration ToVolumeConcentration(Density componentDensity, Molar #region Static Methods /// - /// Get from . + /// Get from . /// /// /// @@ -61,7 +64,8 @@ public static Molarity FromDensity(Density density, Mass molecularWeight) } /// - /// Get from and known component and . + /// Get from and known component and + /// . /// /// /// @@ -88,19 +92,24 @@ public static Molarity FromVolumeConcentration(VolumeConcentration volumeConcent return MassConcentration.FromGramsPerCubicMeter(molarity.MolesPerCubicMeter * componentMass.GramsPerMole); } - /// Get from diluting the current by the given . + /// + /// Get from diluting the current by the given + /// . + /// public static Molarity operator *(Molarity molarity, VolumeConcentration volumeConcentration) { return new Molarity(molarity.MolesPerCubicMeter * volumeConcentration.DecimalFractions, MolarityUnit.MolesPerCubicMeter); } - /// Get from diluting the current by the given . + /// + /// Get from diluting the current by the given + /// . + /// public static Molarity operator *(VolumeConcentration volumeConcentration, Molarity molarity) { return new Molarity(molarity.MolesPerCubicMeter * volumeConcentration.DecimalFractions, MolarityUnit.MolesPerCubicMeter); } #endregion - } } diff --git a/UnitsNet/CustomCode/Quantities/Power.extra.cs b/UnitsNet/CustomCode/Quantities/Power.extra.cs index 4b61a19b76..426e54a4dd 100644 --- a/UnitsNet/CustomCode/Quantities/Power.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Power.extra.cs @@ -21,76 +21,76 @@ public PowerRatio ToPowerRatio() return PowerRatio.FromPower(this); } - /// Get from times . + /// Get from times . public static Energy operator *(Power power, TimeSpan time) { return Energy.FromJoules(power.Watts * time.TotalSeconds); } - /// Get from times . + /// Get from times . public static Energy operator *(TimeSpan time, Power power) { return Energy.FromJoules(power.Watts * time.TotalSeconds); } - /// Get from times . + /// Get from times . public static Energy operator *(Power power, Duration duration) { return Energy.FromJoules(power.Watts * duration.Seconds); } - /// Get from times . + /// Get from times . public static Energy operator *(Duration duration, Power power) { return Energy.FromJoules(power.Watts * duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static Force operator /(Power power, Speed speed) { return Force.FromNewtons(power.Watts / speed.MetersPerSecond); } - /// Get from divided by . + /// Get from divided by . public static Torque operator /(Power power, RotationalSpeed rotationalSpeed) { return Torque.FromNewtonMeters(power.Watts / rotationalSpeed.RadiansPerSecond); } - /// Get from divided by . + /// Get from divided by . public static RotationalSpeed operator /(Power power, Torque torque) { return RotationalSpeed.FromRadiansPerSecond(power.Watts / torque.NewtonMeters); } - /// Get from times . + /// Get from times . public static MassFlow operator *(Power power, BrakeSpecificFuelConsumption bsfc) { return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule * power.Watts); } - /// Get from divided by . + /// Get from divided by . public static SpecificEnergy operator /(Power power, MassFlow massFlow) { return SpecificEnergy.FromJoulesPerKilogram(power.Watts / massFlow.KilogramsPerSecond); } - /// Get from divided by . + /// Get from divided by . public static MassFlow operator /(Power power, SpecificEnergy specificEnergy) { return MassFlow.FromKilogramsPerSecond(power.Watts / specificEnergy.JoulesPerKilogram); } - /// Get from divided by . + /// Get from divided by . public static HeatFlux operator /(Power power, Area area) { return HeatFlux.FromWattsPerSquareMeter(power.Watts / area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static Area operator /(Power power, HeatFlux heatFlux) { - return Area.FromSquareMeters( power.Watts / heatFlux.WattsPerSquareMeter ); + return Area.FromSquareMeters(power.Watts / heatFlux.WattsPerSquareMeter); } } } diff --git a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs index f563f720ae..e9866b5d24 100644 --- a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs @@ -12,13 +12,14 @@ public partial struct PowerRatio /// Initializes a new instance of the struct from the specified power referenced to one watt. /// /// The power relative to one watt. - public PowerRatio(Power power) : this() { if (power.Watts <= 0) + { throw new ArgumentOutOfRangeException( nameof(power), "The base-10 logarithm of a number ≤ 0 is undefined. Power must be greater than 0 W."); + } // P(dBW) = 10*log10(value(W)/reference(W)) _value = 10 * Math.Log10(power.Watts / 1); diff --git a/UnitsNet/CustomCode/Quantities/Pressure.extra.cs b/UnitsNet/CustomCode/Quantities/Pressure.extra.cs index ecaf977ed6..fa5a83aa16 100644 --- a/UnitsNet/CustomCode/Quantities/Pressure.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Pressure.extra.cs @@ -1,32 +1,34 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using UnitsNet.Units; + namespace UnitsNet { public partial struct Pressure { - /// Get from times . + /// Get from times . public static Force operator *(Pressure pressure, Area area) { return Force.FromNewtons(pressure.Pascals * area.SquareMeters); } - /// Get from times . + /// Get from times . public static Force operator *(Area area, Pressure pressure) { return Force.FromNewtons(pressure.Pascals * area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static Length operator /(Pressure pressure, SpecificWeight specificWeight) { - return new Length(pressure.Pascals / specificWeight.NewtonsPerCubicMeter, UnitsNet.Units.LengthUnit.Meter); + return new Length(pressure.Pascals / specificWeight.NewtonsPerCubicMeter, LengthUnit.Meter); } - /// Get from divided by . + /// Get from divided by . public static SpecificWeight operator /(Pressure pressure, Length length) { - return new SpecificWeight(pressure.Pascals / length.Meters, UnitsNet.Units.SpecificWeightUnit.NewtonPerCubicMeter); + return new SpecificWeight(pressure.Pascals / length.Meters, SpecificWeightUnit.NewtonPerCubicMeter); } } } diff --git a/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs b/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs index a1f18c79cd..411d8ff43e 100644 --- a/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs +++ b/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs @@ -7,25 +7,25 @@ namespace UnitsNet { public partial struct RotationalSpeed { - /// Get from times . + /// Get from times . public static Angle operator *(RotationalSpeed rotationalSpeed, TimeSpan timeSpan) { return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Angle operator *(TimeSpan timeSpan, RotationalSpeed rotationalSpeed) { return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Angle operator *(RotationalSpeed rotationalSpeed, Duration duration) { return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static Angle operator *(Duration duration, RotationalSpeed rotationalSpeed) { return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * duration.Seconds); diff --git a/UnitsNet/CustomCode/Quantities/RotationalStiffness.extra.cs b/UnitsNet/CustomCode/Quantities/RotationalStiffness.extra.cs index 48b9342455..ea7afb93be 100644 --- a/UnitsNet/CustomCode/Quantities/RotationalStiffness.extra.cs +++ b/UnitsNet/CustomCode/Quantities/RotationalStiffness.extra.cs @@ -5,19 +5,25 @@ namespace UnitsNet { public partial struct RotationalStiffness { - /// Get from times . + /// Get from times . public static Torque operator *(RotationalStiffness rotationalStiffness, Angle angle) { return Torque.FromNewtonMeters(rotationalStiffness.NewtonMetersPerRadian * angle.Radians); } - /// Get from divided by . + /// + /// Get from divided by + /// . + /// public static RotationalStiffnessPerLength operator /(RotationalStiffness rotationalStiffness, Length length) { return RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(rotationalStiffness.NewtonMetersPerRadian / length.Meters); } - /// Get from divided by . + /// + /// Get from divided by + /// . + /// public static Length operator /(RotationalStiffness rotationalStiffness, RotationalStiffnessPerLength rotationalStiffnessPerLength) { return Length.FromMeters(rotationalStiffness.NewtonMetersPerRadian / rotationalStiffnessPerLength.NewtonMetersPerRadianPerMeter); diff --git a/UnitsNet/CustomCode/Quantities/RotationalStiffnessPerLength.extra.cs b/UnitsNet/CustomCode/Quantities/RotationalStiffnessPerLength.extra.cs index 1aef772c05..33ad3bbd53 100644 --- a/UnitsNet/CustomCode/Quantities/RotationalStiffnessPerLength.extra.cs +++ b/UnitsNet/CustomCode/Quantities/RotationalStiffnessPerLength.extra.cs @@ -2,11 +2,15 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. // ReSharper disable once CheckNamespace + namespace UnitsNet { public partial struct RotationalStiffnessPerLength { - /// Get from times . + /// + /// Get from times + /// . + /// public static RotationalStiffness operator *(RotationalStiffnessPerLength rotationalStiffness, Length length) { return RotationalStiffness.FromNewtonMetersPerRadian(rotationalStiffness.NewtonMetersPerRadianPerMeter * length.Meters); diff --git a/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs b/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs index 45f4473f80..c8d3dcfcaa 100644 --- a/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs +++ b/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs @@ -5,31 +5,37 @@ namespace UnitsNet { public partial struct SpecificEnergy { - /// Get from times . + /// Get from times . public static Energy operator *(SpecificEnergy specificEnergy, Mass mass) { return Energy.FromJoules(specificEnergy.JoulesPerKilogram * mass.Kilograms); } - /// Get from times . + /// Get from times . public static Energy operator *(Mass mass, SpecificEnergy specificEnergy) { return Energy.FromJoules(specificEnergy.JoulesPerKilogram * mass.Kilograms); } - /// Get from divided by . + /// + /// Get from divided by + /// . + /// public static BrakeSpecificFuelConsumption operator /(double value, SpecificEnergy specificEnergy) { return BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value / specificEnergy.JoulesPerKilogram); } - /// Get from times . + /// + /// Get from times + /// . + /// public static double operator *(SpecificEnergy specificEnergy, BrakeSpecificFuelConsumption bsfc) { return specificEnergy.JoulesPerKilogram * bsfc.KilogramsPerJoule; } - /// Get from times . + /// Get from times . public static Power operator *(SpecificEnergy specificEnergy, MassFlow massFlow) { return Power.FromWatts(massFlow.KilogramsPerSecond * specificEnergy.JoulesPerKilogram); diff --git a/UnitsNet/CustomCode/Quantities/SpecificVolume.extra.cs b/UnitsNet/CustomCode/Quantities/SpecificVolume.extra.cs index f284f8bb28..7b14c6dc1f 100644 --- a/UnitsNet/CustomCode/Quantities/SpecificVolume.extra.cs +++ b/UnitsNet/CustomCode/Quantities/SpecificVolume.extra.cs @@ -5,13 +5,13 @@ namespace UnitsNet { public partial struct SpecificVolume { - /// Get from divided by . + /// Get from divided by . public static Density operator /(double constant, SpecificVolume volume) { return Density.FromKilogramsPerCubicMeter(constant / volume.CubicMetersPerKilogram); } - /// Get from times . + /// Get from times . public static Volume operator *(SpecificVolume volume, Mass mass) { return Volume.FromCubicMeters(volume.CubicMetersPerKilogram * mass.Kilograms); diff --git a/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs b/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs index 85f4f8bae1..66b6b0413d 100644 --- a/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs +++ b/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs @@ -7,34 +7,34 @@ namespace UnitsNet { public partial struct SpecificWeight { - /// Get from times . + /// Get from times . public static Pressure operator *(SpecificWeight specificWeight, Length length) { - return new Pressure(specificWeight.NewtonsPerCubicMeter * length.Meters, UnitsNet.Units.PressureUnit.Pascal); + return new Pressure(specificWeight.NewtonsPerCubicMeter * length.Meters, PressureUnit.Pascal); } - /// Get from times . + /// Get from times . public static ForcePerLength operator *(SpecificWeight specificWeight, Area area) { return new ForcePerLength(specificWeight.NewtonsPerCubicMeter * area.SquareMeters, ForcePerLengthUnit.NewtonPerMeter); } - /// Get from times . + /// Get from times . public static ForcePerLength operator *(Area area, SpecificWeight specificWeight) { return new ForcePerLength(area.SquareMeters * specificWeight.NewtonsPerCubicMeter, ForcePerLengthUnit.NewtonPerMeter); } - /// Get from divided by . + /// Get from divided by . public static Acceleration operator /(SpecificWeight specificWeight, Density density) { - return new Acceleration(specificWeight.NewtonsPerCubicMeter / density.KilogramsPerCubicMeter, UnitsNet.Units.AccelerationUnit.MeterPerSecondSquared); + return new Acceleration(specificWeight.NewtonsPerCubicMeter / density.KilogramsPerCubicMeter, AccelerationUnit.MeterPerSecondSquared); } - /// Get from divided by . + /// Get from divided by . public static Density operator /(SpecificWeight specific, Acceleration acceleration) { - return new Density(specific.NewtonsPerCubicMeter / acceleration.MetersPerSecondSquared, UnitsNet.Units.DensityUnit.KilogramPerCubicMeter); + return new Density(specific.NewtonsPerCubicMeter / acceleration.MetersPerSecondSquared, DensityUnit.KilogramPerCubicMeter); } } } diff --git a/UnitsNet/CustomCode/Quantities/Speed.extra.cs b/UnitsNet/CustomCode/Quantities/Speed.extra.cs index 549fff0bea..b4675b594b 100644 --- a/UnitsNet/CustomCode/Quantities/Speed.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Speed.extra.cs @@ -7,61 +7,61 @@ namespace UnitsNet { public partial struct Speed { - /// Get from divided by . + /// Get from divided by . public static Acceleration operator /(Speed speed, TimeSpan timeSpan) { return Acceleration.FromMetersPerSecondSquared(speed.MetersPerSecond / timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Length operator *(Speed speed, TimeSpan timeSpan) { return Length.FromMeters(speed.MetersPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Length operator *(TimeSpan timeSpan, Speed speed) { return Length.FromMeters(speed.MetersPerSecond * timeSpan.TotalSeconds); } - /// Get from divided by . + /// Get from divided by . public static Acceleration operator /(Speed speed, Duration duration) { return Acceleration.FromMetersPerSecondSquared(speed.MetersPerSecond / duration.Seconds); } - /// Get from times . + /// Get from times . public static Length operator *(Speed speed, Duration duration) { return Length.FromMeters(speed.MetersPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static Length operator *(Duration duration, Speed speed) { return Length.FromMeters(speed.MetersPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static KinematicViscosity operator *(Speed speed, Length length) { return KinematicViscosity.FromSquareMetersPerSecond(length.Meters * speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static SpecificEnergy operator *(Speed left, Speed right) { return SpecificEnergy.FromJoulesPerKilogram(left.MetersPerSecond * right.MetersPerSecond); } - /// Get from times . + /// Get from times . public static MassFlux operator *(Speed speed, Density density) { return MassFlux.FromKilogramsPerSecondPerSquareMeter(speed.MetersPerSecond * density.KilogramsPerCubicMeter); } - /// Get from times . + /// Get from times . public static VolumeFlow operator *(Speed speed, Area area) { return VolumeFlow.FromCubicMetersPerSecond(speed.MetersPerSecond * area.SquareMeters); diff --git a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs index cfce09a948..93b7495e03 100644 --- a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs @@ -60,7 +60,7 @@ public partial struct Temperature /// The resulting . public Temperature Multiply(double factor, TemperatureUnit unit) { - double resultInUnit = As(unit) * factor; + var resultInUnit = As(unit) * factor; return From(resultInUnit, unit); } @@ -78,7 +78,7 @@ public Temperature Multiply(double factor, TemperatureUnit unit) /// The resulting . public Temperature Divide(double divisor, TemperatureUnit unit) { - double resultInUnit = As(unit) / divisor; + var resultInUnit = As(unit) / divisor; return From(resultInUnit, unit); } } diff --git a/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs b/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs index b3b3878cbb..b9df5787cd 100644 --- a/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs +++ b/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs @@ -5,19 +5,19 @@ namespace UnitsNet { public partial struct TemperatureDelta { - /// Get from divided by . + /// Get from divided by . public static LapseRate operator /(TemperatureDelta left, Length right) { return LapseRate.FromDegreesCelciusPerKilometer(left.DegreesCelsius / right.Kilometers); } - /// Get from times . + /// Get from times . public static SpecificEnergy operator *(SpecificEntropy specificEntropy, TemperatureDelta temperatureDelta) { return SpecificEnergy.FromJoulesPerKilogram(specificEntropy.JoulesPerKilogramKelvin * temperatureDelta.Kelvins); } - /// Get from times . + /// Get from times . public static SpecificEnergy operator *(TemperatureDelta temperatureDelta, SpecificEntropy specificEntropy) { return specificEntropy * temperatureDelta; diff --git a/UnitsNet/CustomCode/Quantities/Torque.extra.cs b/UnitsNet/CustomCode/Quantities/Torque.extra.cs index 26bd4f551b..e6f9d759fa 100644 --- a/UnitsNet/CustomCode/Quantities/Torque.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Torque.extra.cs @@ -5,25 +5,25 @@ namespace UnitsNet { public partial struct Torque { - /// Get from times . + /// Get from times . public static Force operator /(Torque torque, Length length) { return Force.FromNewtons(torque.NewtonMeters / length.Meters); } - /// Get from times . + /// Get from times . public static Length operator /(Torque torque, Force force) { return Length.FromMeters(torque.NewtonMeters / force.Newtons); } - /// Get from times . + /// Get from times . public static RotationalStiffness operator /(Torque torque, Angle angle) { return RotationalStiffness.FromNewtonMetersPerRadian(torque.NewtonMeters / angle.Radians); } - /// Get from times . + /// Get from times . public static Angle operator /(Torque torque, RotationalStiffness rotationalStiffness) { return Angle.FromRadians(torque.NewtonMeters / rotationalStiffness.NewtonMetersPerRadian); diff --git a/UnitsNet/CustomCode/Quantities/Volume.extra.cs b/UnitsNet/CustomCode/Quantities/Volume.extra.cs index aab43915a4..2d991530e9 100644 --- a/UnitsNet/CustomCode/Quantities/Volume.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Volume.extra.cs @@ -7,31 +7,31 @@ namespace UnitsNet { public partial struct Volume { - /// Get from divided by . + /// Get from divided by . public static Area operator /(Volume volume, Length length) { return Area.FromSquareMeters(volume.CubicMeters / length.Meters); } - /// Get from divided by . + /// Get from divided by . public static Length operator /(Volume volume, Area area) { return Length.FromMeters(volume.CubicMeters / area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static VolumeFlow operator /(Volume volume, Duration duration) { return VolumeFlow.FromCubicMetersPerSecond(volume.CubicMeters / duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static VolumeFlow operator /(Volume volume, TimeSpan timeSpan) { return VolumeFlow.FromCubicMetersPerSecond(volume.CubicMeters / timeSpan.TotalSeconds); } - /// Get from divided by . + /// Get from divided by . public static TimeSpan operator /(Volume volume, VolumeFlow volumeFlow) { return TimeSpan.FromSeconds(volume.CubicMeters / volumeFlow.CubicMetersPerSecond); diff --git a/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs b/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs index e90942cfd1..dd81003100 100644 --- a/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs @@ -1,11 +1,15 @@ -using UnitsNet.Units; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using UnitsNet.Units; namespace UnitsNet { public partial struct VolumeConcentration { /// - /// Get from this and component . + /// Get from this and component + /// . /// /// /// @@ -15,7 +19,8 @@ public MassConcentration ToMassConcentration(Density componentDensity) } /// - /// Get from this and component and . + /// Get from this and component and + /// . /// /// /// @@ -28,7 +33,8 @@ public Molarity ToMolarity(Density componentDensity, MolarMass compontMolarMass) #region Static Methods /// - /// Get from a component and total mixture . + /// Get from a component and total mixture + /// . /// public static VolumeConcentration FromVolumes(Volume componentVolume, Volume mixtureMass) { @@ -36,7 +42,8 @@ public static VolumeConcentration FromVolumes(Volume componentVolume, Volume mix } /// - /// Get a from and a component and . + /// Get a from and a component and + /// . /// /// /// @@ -46,24 +53,28 @@ public static VolumeConcentration FromMolarity(Molarity molarity, Density compon return molarity * componentMolarMass / componentDensity; } - #endregion #region Operators - /// Get from times the component . + /// + /// Get from times the component + /// . + /// public static MassConcentration operator *(VolumeConcentration volumeConcentration, Density componentDensity) { return MassConcentration.FromKilogramsPerCubicMeter(volumeConcentration.DecimalFractions * componentDensity.KilogramsPerCubicMeter); } - - /// Get from times the component . + + /// + /// Get from times the component + /// . + /// public static MassConcentration operator *(Density componentDensity, VolumeConcentration volumeConcentration) { return MassConcentration.FromKilogramsPerCubicMeter(volumeConcentration.DecimalFractions * componentDensity.KilogramsPerCubicMeter); } - - #endregion + #endregion } } diff --git a/UnitsNet/CustomCode/Quantities/VolumeFlow.extra.cs b/UnitsNet/CustomCode/Quantities/VolumeFlow.extra.cs index 51e71e8180..90b8c36e85 100644 --- a/UnitsNet/CustomCode/Quantities/VolumeFlow.extra.cs +++ b/UnitsNet/CustomCode/Quantities/VolumeFlow.extra.cs @@ -7,37 +7,37 @@ namespace UnitsNet { public partial struct VolumeFlow { - /// Get from times . + /// Get from times . public static Volume operator *(VolumeFlow volumeFlow, TimeSpan timeSpan) { return Volume.FromCubicMeters(volumeFlow.CubicMetersPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Volume operator *(VolumeFlow volumeFlow, Duration duration) { return Volume.FromCubicMeters(volumeFlow.CubicMetersPerSecond * duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static Speed operator /(VolumeFlow volumeFlow, Area area) { return Speed.FromMetersPerSecond(volumeFlow.CubicMetersPerSecond / area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static Area operator /(VolumeFlow volumeFlow, Speed speed) { return Area.FromSquareMeters(volumeFlow.CubicMetersPerSecond / speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static MassFlow operator *(VolumeFlow volumeFlow, Density density) { return MassFlow.FromKilogramsPerSecond(volumeFlow.CubicMetersPerSecond * density.KilogramsPerCubicMeter); } - /// Get from times . + /// Get from times . public static MassFlow operator *(Density density, VolumeFlow volumeFlow) { return MassFlow.FromKilogramsPerSecond(volumeFlow.CubicMetersPerSecond * density.KilogramsPerCubicMeter); diff --git a/UnitsNet/CustomCode/Quantity.cs b/UnitsNet/CustomCode/Quantity.cs index 74fe89d86d..9592405b90 100644 --- a/UnitsNet/CustomCode/Quantity.cs +++ b/UnitsNet/CustomCode/Quantity.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -24,17 +27,18 @@ static Quantity() } /// - /// All enum values of , such as and . + /// All enum values of , such as and + /// . /// public static QuantityType[] Types { get; } /// - /// All enum value names of , such as "Length" and "Mass". + /// All enum value names of , such as "Length" and "Mass". /// public static string[] Names { get; } /// - /// All quantity information objects, such as and . + /// All quantity information objects, such as and . /// public static QuantityInfo[] Infos => InfosLazy.Value; @@ -43,53 +47,63 @@ static Quantity() /// /// Numeric value. /// Unit enum value. - /// An object. + /// An object. /// Unit value is not a know unit enum type. public static IQuantity From(QuantityValue value, Enum unit) { - if (TryFrom(value, unit, out IQuantity quantity)) + if (TryFrom(value, unit, out var quantity)) + { return quantity; + } throw new ArgumentException( $"Unit value {unit} of type {unit.GetType()} is not a known unit enum type. Expected types like UnitsNet.Units.LengthUnit. Did you pass in a third-party enum type defined outside UnitsNet library?"); } - /// + /// public static bool TryFrom(double value, Enum unit, out IQuantity quantity) { // Implicit cast to QuantityValue would prevent TryFrom from being called, // so we need to explicitly check this here for double arguments. if (double.IsNaN(value) || double.IsInfinity(value)) { - quantity = default(IQuantity); + quantity = default; return false; } - return TryFrom((QuantityValue)value, unit, out quantity); + return TryFrom((QuantityValue) value, unit, out quantity); } - /// + /// public static IQuantity Parse(Type quantityType, string quantityString) => Parse(null, quantityType, quantityString); /// /// Dynamically parse a quantity string representation. /// - /// The format provider to use for lookup. Defaults to if null. - /// Type of quantity, such as . - /// Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// + /// Type of quantity, such as . + /// + /// Quantity string representation, such as "1.5 kg". Must be compatible with given quantity + /// type. + /// /// The parsed quantity. /// Type must be of type UnitsNet.IQuantity -or- Type is not a known quantity type. public static IQuantity Parse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString) { if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) + { throw new ArgumentException($"Type {quantityType} must be of type UnitsNet.IQuantity."); + } - if (TryParse(formatProvider, quantityType, quantityString, out IQuantity quantity)) return quantity; + if (TryParse(formatProvider, quantityType, quantityString, out var quantity)) return quantity; throw new ArgumentException($"Quantity string could not be parsed to quantity {quantityType}."); } - /// + /// public static bool TryParse(Type quantityType, string quantityString, out IQuantity quantity) => TryParse(null, quantityType, quantityString, out quantity); diff --git a/UnitsNet/CustomCode/QuantityParser.cs b/UnitsNet/CustomCode/QuantityParser.cs index 0f4a4028e4..3aa09a2e4f 100644 --- a/UnitsNet/CustomCode/QuantityParser.cs +++ b/UnitsNet/CustomCode/QuantityParser.cs @@ -12,7 +12,6 @@ // ReSharper disable once CheckNamespace namespace UnitsNet { - internal delegate TQuantity QuantityFromDelegate(QuantityValue value, TUnitType fromUnit) where TQuantity : IQuantity where TUnitType : Enum; @@ -20,14 +19,17 @@ internal delegate TQuantity QuantityFromDelegate(Qu internal class QuantityParser { /// - /// Allow integer, floating point or exponential number formats. + /// Allow integer, floating point or exponential number formats. /// private const NumberStyles ParseNumberStyles = NumberStyles.Number | NumberStyles.Float | NumberStyles.AllowExponent; private readonly UnitAbbreviationsCache _unitAbbreviationsCache; private readonly UnitParser _unitParser; - public static QuantityParser Default { get; } + static QuantityParser() + { + Default = new QuantityParser(UnitAbbreviationsCache.Default); + } public QuantityParser(UnitAbbreviationsCache unitAbbreviationsCache) { @@ -35,10 +37,7 @@ public QuantityParser(UnitAbbreviationsCache unitAbbreviationsCache) _unitParser = new UnitParser(_unitAbbreviationsCache); } - static QuantityParser() - { - Default = new QuantityParser(UnitAbbreviationsCache.Default); - } + public static QuantityParser Default { get; } [SuppressMessage("ReSharper", "UseStringInterpolation")] internal TQuantity Parse([NotNull] string str, @@ -55,13 +54,16 @@ internal TQuantity Parse([NotNull] string str, : NumberFormatInfo.CurrentInfo; if (numFormat == null) + { throw new InvalidOperationException($"No number format was found for the given format provider: {formatProvider}"); + } var regex = CreateRegexForQuantity(formatProvider); if (!ExtractValueAndUnit(regex, str, out var valueString, out var unitString)) { - var ex = new FormatException("Unable to parse quantity. Expected the form \"{value} {unit abbreviation}\", such as \"5.5 m\". The spacing is optional."); + var ex = new FormatException( + "Unable to parse quantity. Expected the form \"{value} {unit abbreviation}\", such as \"5.5 m\". The spacing is optional."); ex.Data["input"] = str; throw ex; } @@ -79,26 +81,31 @@ internal bool TryParse([NotNull] string str, { result = default; - if(string.IsNullOrWhiteSpace(str)) return false; + if (string.IsNullOrWhiteSpace(str)) return false; str = str.Trim(); var numFormat = formatProvider != null ? (NumberFormatInfo) formatProvider.GetFormat(typeof(NumberFormatInfo)) : NumberFormatInfo.CurrentInfo; - if(numFormat == null) + if (numFormat == null) + { return false; + } var regex = CreateRegexForQuantity(formatProvider); if (!ExtractValueAndUnit(regex, str, out var valueString, out var unitString)) + { return false; + } return TryParseWithRegex(valueString, unitString, fromDelegate, formatProvider, out result); } /// - /// Workaround for C# not allowing to pass on 'out' param from type Length to IQuantity, even though the are compatible. + /// Workaround for C# not allowing to pass on 'out' param from type Length to IQuantity, even though the are + /// compatible. /// [SuppressMessage("ReSharper", "UseStringInterpolation")] internal bool TryParse([NotNull] string str, @@ -171,10 +178,14 @@ private bool TryParseWithRegex(string valueString, result = default; if (!double.TryParse(valueString, ParseNumberStyles, formatProvider, out var value)) - return false; + { + return false; + } if (!_unitParser.TryParse(unitString, formatProvider, out var parsedUnit)) - return false; + { + return false; + } result = fromDelegate(value, parsedUnit); return true; diff --git a/UnitsNet/CustomCode/UnitAbbreviationsCache.cs b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs index d10b08b5fe..689e2937a8 100644 --- a/UnitsNet/CustomCode/UnitAbbreviationsCache.cs +++ b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs @@ -8,7 +8,6 @@ using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; - using UnitTypeToLookup = System.Collections.Generic.Dictionary; // ReSharper disable once CheckNamespace @@ -16,14 +15,13 @@ namespace UnitsNet { /// /// Cache of the mapping between unit enum values and unit abbreviation strings for one or more cultures. - /// A static instance is used internally for ToString() and Parse() of quantities and units. + /// A static instance is used internally for ToString() and Parse() of quantities and units. /// public sealed partial class UnitAbbreviationsCache { - private readonly Dictionary _lookupsForCulture; - /// - /// Fallback culture used by and + /// Fallback culture used by and + /// /// if no abbreviations are found with a given culture. /// /// @@ -33,10 +31,12 @@ public sealed partial class UnitAbbreviationsCache /// private static readonly CultureInfo FallbackCulture = new CultureInfo("en-US"); - /// - /// The static instance used internally for ToString() and Parse() of quantities and units. - /// - public static UnitAbbreviationsCache Default { get; } + private readonly Dictionary _lookupsForCulture; + + static UnitAbbreviationsCache() + { + Default = new UnitAbbreviationsCache(); + } /// /// Create an instance of the cache and load all the abbreviations defined in the library. @@ -48,14 +48,14 @@ public UnitAbbreviationsCache() LoadGeneratedAbbreviations(); } - static UnitAbbreviationsCache() - { - Default = new UnitAbbreviationsCache(); - } + /// + /// The static instance used internally for ToString() and Parse() of quantities and units. + /// + public static UnitAbbreviationsCache Default { get; } private void LoadGeneratedAbbreviations() { - foreach(var localization in GeneratedLocalizations) + foreach (var localization in GeneratedLocalizations) { var culture = new CultureInfo(localization.CultureName); MapUnitToAbbreviation(localization.UnitType, localization.UnitValue, culture, localization.UnitAbbreviations); @@ -63,9 +63,11 @@ private void LoadGeneratedAbbreviations() } /// - /// Adds one or more unit abbreviation for the given unit enum value. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. + /// Adds one or more unit abbreviation for the given unit enum value. + /// This is used to dynamically add abbreviations for existing unit enums such as + /// or to extend with third-party unit enums + /// in order to or on them + /// later. /// /// The unit enum value. /// Unit abbreviations to add. @@ -77,9 +79,11 @@ public void MapUnitToAbbreviation(TUnitType unit, params string[] abb } /// - /// Adds a unit abbreviation for the given unit enum value and sets it as the default. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. + /// Adds a unit abbreviation for the given unit enum value and sets it as the default. + /// This is used to dynamically add abbreviations for existing unit enums such as + /// or to extend with third-party unit enums + /// in order to or on them + /// later. /// /// The unit enum value. /// Unit abbreviations to add as default. @@ -90,12 +94,17 @@ public void MapUnitToDefaultAbbreviation(TUnitType unit, string abbre } /// - /// Adds one or more unit abbreviation for the given unit enum value. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. + /// Adds one or more unit abbreviation for the given unit enum value. + /// This is used to dynamically add abbreviations for existing unit enums such as or to + /// extend with third-party unit enums + /// in order to or on them + /// later. /// /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// Unit abbreviations to add. /// The type of unit enum. [PublicAPI] @@ -111,12 +120,17 @@ public void MapUnitToAbbreviation(TUnitType unit, IFormatProvider for } /// - /// Adds a unit abbreviation for the given unit enum value and sets it as the default. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. + /// Adds a unit abbreviation for the given unit enum value and sets it as the default. + /// This is used to dynamically add abbreviations for existing unit enums such as or to + /// extend with third-party unit enums + /// in order to or on them + /// later. /// /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// Unit abbreviation to add as default. /// The type of unit enum. [PublicAPI] @@ -132,13 +146,18 @@ public void MapUnitToDefaultAbbreviation(TUnitType unit, IFormatProvi } /// - /// Adds one or more unit abbreviation for the given unit enum value. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. + /// Adds one or more unit abbreviation for the given unit enum value. + /// This is used to dynamically add abbreviations for existing unit enums such as or to + /// extend with third-party unit enums + /// in order to or on them + /// later. /// /// The unit enum type. /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// Unit abbreviations to add. [PublicAPI] public void MapUnitToAbbreviation(Type unitType, int unitValue, IFormatProvider formatProvider, [NotNull] params string[] abbreviations) @@ -147,13 +166,18 @@ public void MapUnitToAbbreviation(Type unitType, int unitValue, IFormatProvider } /// - /// Adds a unit abbreviation for the given unit enum value and sets it as the default. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. + /// Adds a unit abbreviation for the given unit enum value and sets it as the default. + /// This is used to dynamically add abbreviations for existing unit enums such as or to + /// extend with third-party unit enums + /// in order to or on them + /// later. /// /// The unit enum type. /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// Unit abbreviation to add as default. [PublicAPI] public void MapUnitToDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider formatProvider, [NotNull] string abbreviation) @@ -161,21 +185,30 @@ public void MapUnitToDefaultAbbreviation(Type unitType, int unitValue, IFormatPr PerformAbbreviationMapping(unitType, unitValue, formatProvider, true, abbreviation); } - private void PerformAbbreviationMapping(Type unitType, int unitValue, IFormatProvider formatProvider, bool setAsDefault, [NotNull] params string[] abbreviations) + private void PerformAbbreviationMapping(Type unitType, int unitValue, IFormatProvider formatProvider, bool setAsDefault, + [NotNull] params string[] abbreviations) { if (!unitType.Wrap().IsEnum) + { throw new ArgumentException("Must be an enum type.", nameof(unitType)); + } if (abbreviations == null) + { throw new ArgumentNullException(nameof(abbreviations)); + } formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; if (!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) + { quantitiesForProvider = _lookupsForCulture[formatProvider] = new UnitTypeToLookup(); + } if (!quantitiesForProvider.TryGetValue(unitType, out var unitToAbbreviations)) + { unitToAbbreviations = quantitiesForProvider[unitType] = new UnitValueAbbreviationLookup(); + } foreach (var abbr in abbreviations) { @@ -184,11 +217,15 @@ private void PerformAbbreviationMapping(Type unitType, int unitValue, IFormatPro } /// - /// Gets the default abbreviation for a given unit. If a unit has more than one abbreviation defined, then it returns the first one. - /// Example: GetDefaultAbbreviation<LengthUnit>(LengthUnit.Kilometer) => "km" + /// Gets the default abbreviation for a given unit. If a unit has more than one abbreviation defined, then it returns + /// the first one. + /// Example: GetDefaultAbbreviation<LengthUnit>(LengthUnit.Kilometer) => "km" /// /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// The type of unit enum. /// The default unit abbreviation string. [PublicAPI] @@ -196,53 +233,64 @@ public string GetDefaultAbbreviation(TUnitType unit, IFormatProvider { var unitType = typeof(TUnitType); - if(!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) + if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) { - if(formatProvider != FallbackCulture) + if (formatProvider != FallbackCulture) + { return GetDefaultAbbreviation(unit, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); + } + + throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); } var abbreviations = lookup.GetAbbreviationsForUnit(unit); - if(abbreviations.Count == 0) + if (abbreviations.Count == 0) { - if(formatProvider != FallbackCulture) + if (formatProvider != FallbackCulture) + { return GetDefaultAbbreviation(unit, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); + } + + throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); } return abbreviations.First(); } /// - /// Gets the default abbreviation for a given unit type and its numeric enum value. - /// If a unit has more than one abbreviation defined, then it returns the first one. - /// Example: GetDefaultAbbreviation<LengthUnit>(typeof(LengthUnit), 1) => "cm" + /// Gets the default abbreviation for a given unit type and its numeric enum value. + /// If a unit has more than one abbreviation defined, then it returns the first one. + /// Example: GetDefaultAbbreviation<LengthUnit>(typeof(LengthUnit), 1) => "cm" /// /// The unit enum type. /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// The default unit abbreviation string. [PublicAPI] public string GetDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider formatProvider = null) { - if(!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) + if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) { - if(formatProvider != FallbackCulture) + if (formatProvider != FallbackCulture) + { return GetDefaultAbbreviation(unitType, unitValue, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); + } + + throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); } var abbreviations = lookup.GetAbbreviationsForUnit(unitValue); - if(abbreviations.Count == 0) + if (abbreviations.Count == 0) { - if(formatProvider != FallbackCulture) + if (formatProvider != FallbackCulture) + { return GetDefaultAbbreviation(unitType, unitValue, FallbackCulture); - else - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); + } + + throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); } return abbreviations.First(); @@ -253,7 +301,10 @@ public string GetDefaultAbbreviation(Type unitType, int unitValue, IFormatProvid /// /// Enum type for units. /// Enum value for unit. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// Unit abbreviations associated with unit. [PublicAPI] public string[] GetUnitAbbreviations(TUnitType unit, IFormatProvider formatProvider = null) where TUnitType : Enum @@ -266,19 +317,26 @@ public string[] GetUnitAbbreviations(TUnitType unit, IFormatProvider /// /// Enum type for unit. /// Enum value for unit. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// Unit abbreviations associated with unit. [PublicAPI] public string[] GetUnitAbbreviations(Type unitType, int unitValue, IFormatProvider formatProvider = null) { formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; - if(!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) + if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) + { return formatProvider != FallbackCulture ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) : new string[] { }; + } var abbreviations = lookup.GetAbbreviationsForUnit(unitValue); - if(abbreviations.Count == 0) + if (abbreviations.Count == 0) + { return formatProvider != FallbackCulture ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) : new string[] { }; + } return abbreviations.ToArray(); } @@ -287,15 +345,20 @@ public string[] GetUnitAbbreviations(Type unitType, int unitValue, IFormatProvid /// Get all abbreviations for all units of a quantity. /// /// Enum type for unit. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// Unit abbreviations associated with unit. [PublicAPI] public string[] GetAllUnitAbbreviationsForQuantity(Type unitEnumType, IFormatProvider formatProvider = null) { formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; - if(!TryGetUnitValueAbbreviationLookup(unitEnumType, formatProvider, out var lookup)) + if (!TryGetUnitValueAbbreviationLookup(unitEnumType, formatProvider, out var lookup)) + { return formatProvider != FallbackCulture ? GetAllUnitAbbreviationsForQuantity(unitEnumType, FallbackCulture) : new string[] { }; + } return lookup.GetAllUnitAbbreviationsForQuantity(); } @@ -306,11 +369,15 @@ internal bool TryGetUnitValueAbbreviationLookup(Type unitType, IFormatProvider f formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; - if(!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) + if (!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) + { return formatProvider != FallbackCulture ? TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations) : false; + } - if(!quantitiesForProvider.TryGetValue(unitType, out unitToAbbreviations)) + if (!quantitiesForProvider.TryGetValue(unitType, out unitToAbbreviations)) + { return formatProvider != FallbackCulture ? TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations) : false; + } return true; } diff --git a/UnitsNet/CustomCode/UnitParser.cs b/UnitsNet/CustomCode/UnitParser.cs index ef254232a4..a621a1c770 100644 --- a/UnitsNet/CustomCode/UnitParser.cs +++ b/UnitsNet/CustomCode/UnitParser.cs @@ -12,18 +12,17 @@ namespace UnitsNet { /// /// Parses units given a unit abbreviations cache. - /// The static instance is used internally to parse quantities and units using the + /// The static instance is used internally to parse quantities and units using the /// default abbreviations cache for all units and abbreviations defined in the library. /// public sealed class UnitParser { private readonly UnitAbbreviationsCache _unitAbbreviationsCache; - /// - /// The default static instance used internally to parse quantities and units using the - /// default abbreviations cache for all units and abbreviations defined in the library. - /// - public static UnitParser Default { get; } + static UnitParser() + { + Default = new UnitParser(UnitAbbreviationsCache.Default); + } /// /// Create a parser using the given unit abbreviations cache. @@ -34,23 +33,27 @@ public UnitParser(UnitAbbreviationsCache unitAbbreviationsCache) _unitAbbreviationsCache = unitAbbreviationsCache ?? UnitAbbreviationsCache.Default; } - static UnitParser() - { - Default = new UnitParser(UnitAbbreviationsCache.Default); - } + /// + /// The default static instance used internally to parse quantities and units using the + /// default abbreviations cache for all units and abbreviations defined in the library. + /// + public static UnitParser Default { get; } /// - /// Parses a unit abbreviation for a given unit enumeration type. - /// Example: Parse<LengthUnit>("km") => LengthUnit.Kilometer + /// Parses a unit abbreviation for a given unit enumeration type. + /// Example: Parse<LengthUnit>("km") => LengthUnit.Kilometer /// /// - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// /// [PublicAPI] public TUnitType Parse(string unitAbbreviation, [CanBeNull] IFormatProvider formatProvider = null) where TUnitType : Enum { - return (TUnitType)Parse(unitAbbreviation, typeof(TUnitType), formatProvider); + return (TUnitType) Parse(unitAbbreviation, typeof(TUnitType), formatProvider); } /// @@ -62,7 +65,10 @@ public TUnitType Parse(string unitAbbreviation, [CanBeNull] IFormatPr /// respectively. /// /// Unit enum type, such as and . - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// Unit enum value, such as . /// No units match the abbreviation. /// More than one unit matches the abbreviation. @@ -72,20 +78,24 @@ public Enum Parse([NotNull] string unitAbbreviation, Type unitType, [CanBeNull] if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); unitAbbreviation = unitAbbreviation.Trim(); - if(!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) + if (!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) + { throw new UnitNotFoundException($"No abbreviations defined for unit type [{unitType}] for culture [{formatProvider}]."); + } - var unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); + var unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, true); if (unitIntValues.Count == 0) { unitAbbreviation = NormalizeUnitString(unitAbbreviation); - unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, true); } // Narrow the search if too many hits, for example Megabar "Mbar" and Millibar "mbar" need to be distinguished if (unitIntValues.Count > 1) - unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: false); + { + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, false); + } switch (unitIntValues.Count) { @@ -94,7 +104,7 @@ public Enum Parse([NotNull] string unitAbbreviation, Type unitType, [CanBeNull] case 0: throw new UnitNotFoundException($"Unit not found with abbreviation [{unitAbbreviation}] for unit type [{unitType}]."); default: - string unitsCsv = string.Join(", ", unitIntValues.Select(x => Enum.GetName(unitType, x)).ToArray()); + var unitsCsv = string.Join(", ", unitIntValues.Select(x => Enum.GetName(unitType, x)).ToArray()); throw new AmbiguousUnitParseException( $"Cannot parse \"{unitAbbreviation}\" since it could be either of these: {unitsCsv}"); } @@ -132,7 +142,7 @@ internal static string NormalizeUnitString(string unitAbbreviation) } /// - /// Try to parse a unit abbreviation. + /// Try to parse a unit abbreviation. /// /// The string value. /// The unit enum value as out result. @@ -145,10 +155,13 @@ public bool TryParse(string unitAbbreviation, out TUnitType unit) whe } /// - /// Try to parse a unit abbreviation. + /// Try to parse a unit abbreviation. /// /// The string value. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// The unit enum value as out result. /// Type of unit enum. /// True if successful. @@ -157,15 +170,17 @@ public bool TryParse(string unitAbbreviation, [CanBeNull] IFormatProv { unit = default; - if(!TryParse(unitAbbreviation, typeof(TUnitType), formatProvider, out var unitObj)) + if (!TryParse(unitAbbreviation, typeof(TUnitType), formatProvider, out var unitObj)) + { return false; + } - unit = (TUnitType)unitObj; + unit = (TUnitType) unitObj; return true; } /// - /// Try to parse a unit abbreviation. + /// Try to parse a unit abbreviation. /// /// The string value. /// Type of unit enum. @@ -178,11 +193,14 @@ public bool TryParse(string unitAbbreviation, Type unitType, out Enum unit) } /// - /// Try to parse a unit abbreviation. + /// Try to parse a unit abbreviation. /// /// The string value. /// Type of unit enum. - /// The format provider to use for lookup. Defaults to if null. + /// + /// The format provider to use for lookup. Defaults to + /// if null. + /// /// The unit enum value as out result. /// True if successful. [PublicAPI] @@ -197,25 +215,31 @@ public bool TryParse(string unitAbbreviation, Type unitType, [CanBeNull] IFormat unitAbbreviation = unitAbbreviation.Trim(); unit = default; - if(!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) + if (!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) + { return false; + } - var unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); + var unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, true); if (unitIntValues.Count == 0) { unitAbbreviation = NormalizeUnitString(unitAbbreviation); - unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, true); } // Narrow the search if too many hits, for example Megabar "Mbar" and Millibar "mbar" need to be distinguished if (unitIntValues.Count > 1) - unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: false); + { + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, false); + } - if(unitIntValues.Count != 1) + if (unitIntValues.Count != 1) + { return false; + } - unit = (Enum)Enum.ToObject(unitType, unitIntValues[0]); + unit = (Enum) Enum.ToObject(unitType, unitIntValues[0]); return true; } } diff --git a/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs b/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs index a82d3f7faf..2336d6de97 100644 --- a/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs +++ b/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Linq; - using UnitToAbbreviationMap = System.Collections.Generic.Dictionary>; using AbbreviationToUnitMap = System.Collections.Generic.Dictionary>; @@ -12,16 +11,13 @@ namespace UnitsNet { internal class UnitValueAbbreviationLookup { - private readonly UnitToAbbreviationMap unitToAbbreviationMap = new UnitToAbbreviationMap(); private readonly AbbreviationToUnitMap abbreviationToUnitMap = new AbbreviationToUnitMap(); private readonly AbbreviationToUnitMap lowerCaseAbbreviationToUnitMap = new AbbreviationToUnitMap(); + private readonly UnitToAbbreviationMap unitToAbbreviationMap = new UnitToAbbreviationMap(); internal string[] GetAllUnitAbbreviationsForQuantity() { - return unitToAbbreviationMap.Values.SelectMany((abbreviations) => - { - return abbreviations; - } ).Distinct().ToArray(); + return unitToAbbreviationMap.Values.SelectMany(abbreviations => { return abbreviations; }).Distinct().ToArray(); } internal List GetAbbreviationsForUnit(UnitType unit) where UnitType : Enum @@ -31,8 +27,10 @@ internal List GetAbbreviationsForUnit(UnitType unit) where Uni internal List GetAbbreviationsForUnit(int unit) { - if(!unitToAbbreviationMap.TryGetValue(unit, out var abbreviations)) + if (!unitToAbbreviationMap.TryGetValue(unit, out var abbreviations)) + { unitToAbbreviationMap[unit] = abbreviations = new List(); + } return abbreviations.Distinct().ToList(); } @@ -43,8 +41,10 @@ internal List GetUnitsForAbbreviation(string abbreviation, bool ignoreCase) var key = ignoreCase ? lowerCaseAbbreviation : abbreviation; var map = ignoreCase ? lowerCaseAbbreviationToUnitMap : abbreviationToUnitMap; - if(!map.TryGetValue(key, out List units)) + if (!map.TryGetValue(key, out var units)) + { map[key] = units = new List(); + } return units.Distinct().ToList(); } @@ -53,14 +53,20 @@ internal void Add(int unit, string abbreviation, bool setAsDefault = false) { var lowerCaseAbbreviation = abbreviation.ToLower(); - if(!unitToAbbreviationMap.TryGetValue(unit, out var abbreviationsForUnit)) + if (!unitToAbbreviationMap.TryGetValue(unit, out var abbreviationsForUnit)) + { abbreviationsForUnit = unitToAbbreviationMap[unit] = new List(); + } - if(!abbreviationToUnitMap.TryGetValue(abbreviation, out var unitsForAbbreviation)) + if (!abbreviationToUnitMap.TryGetValue(abbreviation, out var unitsForAbbreviation)) + { abbreviationToUnitMap[abbreviation] = unitsForAbbreviation = new List(); + } - if(!lowerCaseAbbreviationToUnitMap.TryGetValue(lowerCaseAbbreviation, out var unitsForLowerCaseAbbreviation)) + if (!lowerCaseAbbreviationToUnitMap.TryGetValue(lowerCaseAbbreviation, out var unitsForLowerCaseAbbreviation)) + { lowerCaseAbbreviationToUnitMap[lowerCaseAbbreviation] = unitsForLowerCaseAbbreviation = new List(); + } unitsForLowerCaseAbbreviation.Remove(unit); unitsForLowerCaseAbbreviation.Add(unit); @@ -70,10 +76,13 @@ internal void Add(int unit, string abbreviation, bool setAsDefault = false) abbreviationsForUnit.Remove(abbreviation); if (setAsDefault) + { abbreviationsForUnit.Insert(0, abbreviation); + } else + { abbreviationsForUnit.Add(abbreviation); - + } } } } diff --git a/UnitsNet/CustomCode/Units/PressureUnit.g.cs b/UnitsNet/CustomCode/Units/PressureReference.cs similarity index 100% rename from UnitsNet/CustomCode/Units/PressureUnit.g.cs rename to UnitsNet/CustomCode/Units/PressureReference.cs diff --git a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs similarity index 97% rename from UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs rename to UnitsNet/CustomCode/Wrappers/ReferencePressure.cs index d33ce141f0..682d14a619 100644 --- a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs +++ b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs @@ -25,6 +25,20 @@ namespace UnitsNet.CustomCode.Wrappers /// public struct ReferencePressure { + /// + /// Represents the pressure at which _pressure is referenced (1 atm default) + /// + public static Pressure AtmosphericPressure { get; set; } + + private static readonly Pressure DefaultAtmosphericPressure = new Pressure(1, PressureUnit.Atmosphere); + + /// + /// Gets a list of options: , + /// , and + /// + public static List References { get; } = + Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); + /// /// Initializes a new instance of the struct requiring measured /// @@ -45,7 +59,7 @@ public ReferencePressure(Pressure pressure) : this(pressure, BaseReference) /// /// The referenced for the measured /// - public ReferencePressure(Pressure pressure, PressureReference reference) : this(pressure, reference, _defaultAtmosphericPressure) + public ReferencePressure(Pressure pressure, PressureReference reference) : this(pressure, reference, DefaultAtmosphericPressure) { } @@ -71,13 +85,6 @@ public ReferencePressure(Pressure pressure, PressureReference reference, Pressur /// public PressureReference Reference { get; } - /// - /// Gets a list of options: , - /// , and - /// - public static List References { get; } = - Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); - /// /// The base reference representation of for the numeric value stored internally. All /// conversions go via @@ -183,12 +190,5 @@ private double AsBaseReference() throw new NotImplementedException($"Can not convert {Reference} to base reference."); } } - - /// - /// Represents the pressure at which _pressure is referenced (1 atm default) - /// - public static Pressure AtmosphericPressure { get; set; } - - private static readonly Pressure _defaultAtmosphericPressure = new Pressure(1, PressureUnit.Atmosphere); } } diff --git a/UnitsNet/IQuantity.cs b/UnitsNet/IQuantity.cs index 60f522e93f..862afaa029 100644 --- a/UnitsNet/IQuantity.cs +++ b/UnitsNet/IQuantity.cs @@ -28,44 +28,53 @@ public interface IQuantity : IFormattable /// QuantityInfo QuantityInfo { get; } + /// + /// The unit this quantity was constructed with -or- BaseUnit if default ctor was used. + /// + Enum Unit { get; } + + /// + /// The value this quantity was constructed with. See also . + /// + double Value { get; } + /// /// Gets the value in the given unit. /// - /// The unit enum value. The unit must be compatible, so for you should provide a value. + /// + /// The unit enum value. The unit must be compatible, so for you should provide a + /// value. + /// /// Value converted to the specified unit. /// Wrong unit enum type was given. double As(Enum unit); /// - /// Gets the value in the unit determined by the given . If multiple units were found for the given , + /// Gets the value in the unit determined by the given . If multiple units were found for the + /// given , /// the first match will be used. /// - /// The to convert the quantity value to. + /// The to convert the quantity value to. /// The converted value. double As(UnitSystem unitSystem); /// - /// The unit this quantity was constructed with -or- BaseUnit if default ctor was used. - /// - Enum Unit { get; } - - /// - /// The value this quantity was constructed with. See also . + /// Converts to a quantity with the given unit representation, which affects things like + /// . /// - double Value { get; } - - /// - /// Converts to a quantity with the given unit representation, which affects things like . - /// - /// The unit enum value. The unit must be compatible, so for you should provide a value. + /// + /// The unit enum value. The unit must be compatible, so for you should provide a + /// value. + /// /// A new quantity with the given unit. IQuantity ToUnit(Enum unit); /// - /// Converts to a quantity with a unit determined by the given , which affects things like . - /// If multiple units were found for the given , the first match will be used. + /// Converts to a quantity with a unit determined by the given , which affects things like + /// . + /// If multiple units were found for the given , the first match will be used. /// - /// The to convert the quantity to. + /// The to convert the quantity to. /// A new quantity with the determined unit. IQuantity ToUnit(UnitSystem unitSystem); @@ -73,7 +82,10 @@ public interface IQuantity : IFormattable /// Gets the string representation of value and unit. Uses two significant digits after radix. /// /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. + /// + /// Format to use for localization and number formatting. Defaults to + /// if null. + /// string ToString([CanBeNull] IFormatProvider provider); /// @@ -81,8 +93,12 @@ public interface IQuantity : IFormattable /// /// The number of significant digits after the radix point. /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] + /// + /// Format to use for localization and number formatting. Defaults to + /// if null. + /// + [Obsolete( + @"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix); /// @@ -91,14 +107,17 @@ public interface IQuantity : IFormattable /// 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. - /// Format to use for localization and number formatting. Defaults to if null. + /// + /// Format to use for localization and number formatting. Defaults to + /// if null. + /// [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args); } /// /// A stronger typed interface where the unit enum type is known, to avoid passing in the - /// wrong unit enum type and not having to cast from . + /// wrong unit enum type and not having to cast from . /// /// /// IQuantity{LengthUnit} length; @@ -106,30 +125,32 @@ public interface IQuantity : IFormattable /// public interface IQuantity : IQuantity where TUnitType : Enum { + /// + new TUnitType Unit { get; } + + /// + new QuantityInfo QuantityInfo { get; } + /// - /// Convert to a unit representation . + /// Convert to a unit representation . /// /// Value converted to the specified unit. double As(TUnitType unit); - /// - new TUnitType Unit { get; } - - /// - new QuantityInfo QuantityInfo { get; } - /// - /// Converts to a quantity with the given unit representation, which affects things like . + /// Converts to a quantity with the given unit representation, which affects things like + /// . /// /// The unit enum value. /// A new quantity with the given unit. IQuantity ToUnit(TUnitType unit); /// - /// Converts to a quantity with a unit determined by the given , which affects things like . - /// If multiple units were found for the given , the first match will be used. + /// Converts to a quantity with a unit determined by the given , which affects things like + /// . + /// If multiple units were found for the given , the first match will be used. /// - /// The to convert the quantity to. + /// The to convert the quantity to. /// A new quantity with the determined unit. new IQuantity ToUnit(UnitSystem unitSystem); } diff --git a/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs b/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs index 0232e43834..95423d683a 100644 --- a/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs +++ b/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs @@ -1,14 +1,14 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using System; -using System.Collections.Generic; -using System.Reflection; #if NET40 || NET35 || NET20 || SILVERLIGHT using UniformTypeInfo = System.Type; #else using UniformTypeInfo = System.Reflection.TypeInfo; #endif +using System; +using System.Collections.Generic; +using System.Reflection; // Based on // https://github.com/StefH/ReflectionBridge/blob/c1e34e57fe3fc93507e83d5cebc1677396645397/ReflectionBridge/src/ReflectionBridge/Extensions/ReflectionBridgeExtensions.cs @@ -47,9 +47,11 @@ internal IEnumerable GetDeclaredMethods() #if NET40 || NET35 || NET20 || SILVERLIGHT foreach (MethodInfo m in t.GetMethods()) #else - foreach (MethodInfo m in t.DeclaredMethods) + foreach (var m in t.DeclaredMethods) #endif + { yield return m; + } t = t.BaseType?.ToUniformType(); } diff --git a/UnitsNet/QuantityFormatter.cs b/UnitsNet/QuantityFormatter.cs index 782c2de23c..c70af40a89 100644 --- a/UnitsNet/QuantityFormatter.cs +++ b/UnitsNet/QuantityFormatter.cs @@ -9,29 +9,33 @@ namespace UnitsNet { /// - /// The QuantityFormatter class is responsible for formatting a quantity using the given format string. + /// The QuantityFormatter class is responsible for formatting a quantity using the given format string. /// public class QuantityFormatter { /// - /// Formats the given quantity using the given format string and format provider. + /// Formats the given quantity using the given format string and format provider. /// - /// The quantity's unit type, for example . + /// The quantity's unit type, for example . /// The quantity to format. /// The format string. - /// The format provider to use for localization and number formatting. Defaults to - /// if null. + /// + /// The format provider to use for localization and number formatting. Defaults to + /// if null. + /// /// - /// The valid format strings are as follows: - /// "g": The value with 2 significant digits after the radix followed by the unit abbreviation, such as "1.23 m". - /// "a": The default unit abbreviation for , such as "m". - /// "a0", "a1", ..., "aN": The Nth unit abbreviation for . "a0" is the same as "a". - /// A will be thrown if the requested abbreviation index does not exist. - /// "v": String representation of . - /// "u": The enum name of , such as "Meter". - /// "q": The quantity name, such as "Length". - /// "s1", "s2", ..., "sN": The value with N significant digits after the radix followed by the unit abbreviation. For example, - /// "s4" would return "1.2345 m" if is 1.2345678. Trailing zeros are omitted. + /// The valid format strings are as follows: + /// "g": The value with 2 significant digits after the radix followed by the unit abbreviation, such as "1.23 m". + /// "a": The default unit abbreviation for , such as "m". + /// "a0", "a1", ..., "aN": The Nth unit abbreviation for . "a0" is the same as + /// "a". + /// A will be thrown if the requested abbreviation index does not exist. + /// "v": String representation of . + /// "u": The enum name of , such as "Meter". + /// "q": The quantity name, such as "Length". + /// "s1", "s2", ..., "sN": The value with N significant digits after the radix followed by the unit abbreviation. For + /// example, + /// "s4" would return "1.2345 m" if is 1.2345678. Trailing zeros are omitted. /// /// The string representation. public static string Format(IQuantity quantity, string format, IFormatProvider formatProvider) @@ -42,26 +46,32 @@ public static string Format(IQuantity quantity, string for var number = 0; var formatString = format; - if(string.IsNullOrEmpty(formatString)) + if (string.IsNullOrEmpty(formatString)) + { formatString = "g"; + } - if(formatString.StartsWith("a") || formatString.StartsWith("s")) + if (formatString.StartsWith("a") || formatString.StartsWith("s")) { - if(formatString.Length > 1 && !int.TryParse(formatString.Substring(1), out number)) + if (formatString.Length > 1 && !int.TryParse(formatString.Substring(1), out number)) + { throw new FormatException($"The {format} format string is not supported."); + } formatString = formatString.Substring(0, 1); } - switch(formatString) + switch (formatString) { case "g": return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, 2); case "a": var abbreviations = UnitAbbreviationsCache.Default.GetUnitAbbreviations(quantity.Unit, formatProvider); - if(number >= abbreviations.Length) + if (number >= abbreviations.Length) + { throw new FormatException($"The {format} format string is invalid because the abbreviation index does not exist."); + } return abbreviations[number]; case "v": @@ -77,10 +87,11 @@ public static string Format(IQuantity quantity, string for } } - private static string ToStringWithSignificantDigitsAfterRadix(IQuantity quantity, IFormatProvider formatProvider, int number) where TUnitType : Enum + private static string ToStringWithSignificantDigitsAfterRadix(IQuantity quantity, IFormatProvider formatProvider, int number) + where TUnitType : Enum { - string formatForSignificantDigits = UnitFormatter.GetFormat(quantity.Value, number); - object[] formatArgs = UnitFormatter.GetFormatArgs(quantity.Unit, quantity.Value, formatProvider, Enumerable.Empty()); + var formatForSignificantDigits = UnitFormatter.GetFormat(quantity.Value, number); + var formatArgs = UnitFormatter.GetFormatArgs(quantity.Unit, quantity.Value, formatProvider, Enumerable.Empty()); return string.Format(formatProvider, formatForSignificantDigits, formatArgs); } } diff --git a/UnitsNet/QuantityInfo.cs b/UnitsNet/QuantityInfo.cs index 2dcdd4cb21..edeea6b988 100644 --- a/UnitsNet/QuantityInfo.cs +++ b/UnitsNet/QuantityInfo.cs @@ -40,10 +40,11 @@ public class QuantityInfo /// The base dimensions of the quantity. /// Quantity type can not be undefined. /// If units -or- baseUnit -or- zero -or- baseDimensions is null. - public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [NotNull] Enum baseUnit, [NotNull] IQuantity zero, [NotNull] BaseDimensions baseDimensions) + public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [NotNull] Enum baseUnit, [NotNull] IQuantity zero, + [NotNull] BaseDimensions baseDimensions) { - if(quantityType == QuantityType.Undefined) throw new ArgumentException("Quantity type can not be undefined.", nameof(quantityType)); - if(baseUnit == null) throw new ArgumentNullException(nameof(baseUnit)); + if (quantityType == QuantityType.Undefined) throw new ArgumentException("Quantity type can not be undefined.", nameof(quantityType)); + if (baseUnit == null) throw new ArgumentNullException(nameof(baseUnit)); BaseDimensions = baseDimensions ?? throw new ArgumentNullException(nameof(baseDimensions)); Zero = zero ?? throw new ArgumentNullException(nameof(zero)); @@ -60,8 +61,8 @@ public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [ // Obsolete members #pragma warning disable 618 - UnitNames = UnitInfos.Select( unitInfo => unitInfo.Name ).ToArray(); - Units = UnitInfos.Select( unitInfo => unitInfo.Value ).ToArray(); + UnitNames = UnitInfos.Select(unitInfo => unitInfo.Name).ToArray(); + Units = UnitInfos.Select(unitInfo => unitInfo.Value).ToArray(); BaseUnit = BaseUnitInfo.Value; #pragma warning restore 618 } @@ -111,12 +112,12 @@ public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [ public IQuantity Zero { get; } /// - /// Unit enum type, such as or . + /// Unit enum type, such as or . /// public Type UnitType { get; } /// - /// Quantity value type, such as or . + /// Quantity value type, such as or . /// public Type ValueType { get; } @@ -126,18 +127,29 @@ public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [ public BaseDimensions BaseDimensions { get; } /// - /// Gets the whose is a subset of . + /// Gets the whose is a subset of . /// - /// Length.Info.GetUnitInfoFor(unitSystemWithFootAsLengthUnit) returns for . - /// The to check against. - /// The that has that is a subset of . - /// is null. - /// No unit was found that is a subset of . - /// More than one unit was found that is a subset of . + /// + /// Length.Info.GetUnitInfoFor(unitSystemWithFootAsLengthUnit) returns for + /// . + /// + /// The to check against. + /// + /// The that has that is a subset of + /// . + /// + /// is null. + /// No unit was found that is a subset of . + /// + /// More than one unit was found that is a subset of + /// . + /// public UnitInfo GetUnitInfoFor(BaseUnits baseUnits) { - if(baseUnits == null) + if (baseUnits == null) + { throw new ArgumentNullException(nameof(baseUnits)); + } var matchingUnitInfos = GetUnitInfosFor(baseUnits) .Take(2) @@ -145,26 +157,36 @@ public UnitInfo GetUnitInfoFor(BaseUnits baseUnits) var firstUnitInfo = matchingUnitInfos.FirstOrDefault(); if (firstUnitInfo == null) + { throw new InvalidOperationException($"No unit was found that is a subset of {nameof(baseUnits)}"); + } if (matchingUnitInfos.Length > 1) + { throw new InvalidOperationException($"More than one unit was found that is a subset of {nameof(baseUnits)}"); + } return firstUnitInfo; } /// - /// Gets an of that have that is a subset of . + /// Gets an of that have that is a + /// subset of . /// - /// The to check against. - /// An of that have that is a subset of . - /// is null. + /// The to check against. + /// + /// An of that have that is a + /// subset of . + /// + /// is null. public IEnumerable GetUnitInfosFor(BaseUnits baseUnits) { - if(baseUnits == null) + if (baseUnits == null) + { throw new ArgumentNullException(nameof(baseUnits)); + } - return UnitInfos.Where((unitInfo) => unitInfo.BaseUnits.IsSubsetOf(baseUnits)); + return UnitInfos.Where(unitInfo => unitInfo.BaseUnits.IsSubsetOf(baseUnits)); } } @@ -188,7 +210,7 @@ public QuantityInfo(QuantityType quantityType, UnitInfo[] unitInfos, TUni // Obsolete members #pragma warning disable 618 - Units = UnitInfos.Select( unitInfo => unitInfo.Value ).ToArray(); + Units = UnitInfos.Select(unitInfo => unitInfo.Value).ToArray(); BaseUnit = BaseUnitInfo.Value; #pragma warning restore 618 } @@ -216,7 +238,7 @@ public QuantityInfo(QuantityType quantityType, UnitInfo[] unitInfos, TUni /// public new UnitInfo GetUnitInfoFor(BaseUnits baseUnits) { - return (UnitInfo)base.GetUnitInfoFor(baseUnits); + return (UnitInfo) base.GetUnitInfoFor(baseUnits); } /// diff --git a/UnitsNet/QuantityTypeConverter.cs b/UnitsNet/QuantityTypeConverter.cs index 63bb261d7e..a54b0dd25c 100644 --- a/UnitsNet/QuantityTypeConverter.cs +++ b/UnitsNet/QuantityTypeConverter.cs @@ -8,118 +8,120 @@ namespace UnitsNet { /// - /// Is the base class for all attributes that are related to + /// Is the base class for all attributes that are related to /// - [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] + [AttributeUsage(AttributeTargets.Property)] public abstract class UnitAttributeBase : Attribute { /// - /// The unit enum type, such as - /// - public Enum UnitType { get; set; } - - /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// public UnitAttributeBase(object unitType) { UnitType = unitType as Enum; } + + /// + /// The unit enum type, such as + /// + public Enum UnitType { get; set; } } /// - /// This attribute defines the default Unit to use if the string to convert only consists of digits + /// This attribute defines the default Unit to use if the string to convert only consists of digits /// public class DefaultUnitAttribute : UnitAttributeBase { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The unit the quantity gets when the string parsing dose only consist of digits - public DefaultUnitAttribute(object unitType) : base(unitType) { } + public DefaultUnitAttribute(object unitType) : base(unitType) + { + } } /// - /// This attribute defines the Unit the quantity is converted to after it has been parsed. + /// This attribute defines the Unit the quantity is converted to after it has been parsed. /// public class ConvertToUnitAttribute : DefaultUnitAttribute { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The unit the quantity is converted to when parsing from string - public ConvertToUnitAttribute(object unitType) : base(unitType) { } + public ConvertToUnitAttribute(object unitType) : base(unitType) + { + } } /// - /// This attribute defines the unit the quantity has when converting to string + /// This attribute defines the unit the quantity has when converting to string /// public class DisplayAsUnitAttribute : DefaultUnitAttribute { /// - /// The formating used when the quantity is converted to string. See - /// - public string Format { get; set; } - - /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The unit the quantity should be displayed in - /// Formating string + /// Formating string public DisplayAsUnitAttribute(object unitType, string format = "") : base(unitType) { Format = format; } + + /// + /// The formating used when the quantity is converted to string. See + /// + /// + public string Format { get; set; } } /// - /// - /// Converts between IQuantity and string. - /// Implements a TypeConverter for IQuantitys. This allows eg the PropertyGrid to read and write properties of type IQuantity. - /// - /// For basic understanding of TypeConverters consult the .NET documentation. + /// + /// Converts between IQuantity and string. + /// Implements a TypeConverter for IQuantitys. This allows eg the PropertyGrid to read and write properties of type + /// IQuantity. + /// + /// For basic understanding of TypeConverters consult the .NET documentation. /// - /// Quantity value type, such as or . + /// Quantity value type, such as or . /// - /// - /// When a string is converted a Quantity the unit given by the string is used. - /// When no unit is given by the string the base unit is used. - /// The base unit can be overwritten by use of the . - /// The converted Quantity can be forced to be in a certain unit by use of the . - /// - /// - /// The displayed unit can be forced to a certain unit by use of the . - /// The provides the possibility to format the displayed Quantity. - /// + /// + /// When a string is converted a Quantity the unit given by the string is used. + /// When no unit is given by the string the base unit is used. + /// The base unit can be overwritten by use of the . + /// The converted Quantity can be forced to be in a certain unit by use of the + /// . + /// + /// + /// The displayed unit can be forced to a certain unit by use of the . + /// The provides the possibility to format the displayed Quantity. + /// /// /// - /// These examples show how to use this TypeConverter. - /// - /// + /// These examples show how to use this TypeConverter. + /// /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length PropertyName { get; set; } /// - /// - /// + /// /// [DisplayAsUnit(UnitsNet.Units.LengthUnit.Meter)] /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length Length { get; set; } /// - /// - /// + /// /// [DisplayAsUnit(UnitsNet.Units.LengthUnit.Meter, "g")] /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length Length { get; set; } /// - /// - /// + /// /// [ConvertToUnitAttribute(UnitsNet.Units.LengthUnit.Meter)] /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length Length { get; set; } /// - /// - /// + /// /// [DefaultUnitAttribute(UnitsNet.Units.LengthUnit.Meter)] /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length Length { get; set; } @@ -128,27 +130,27 @@ public DisplayAsUnitAttribute(object unitType, string format = "") : base(unitTy public class QuantityTypeConverter : TypeConverter where TQuantity : IQuantity { /// - /// Returns true if sourceType if of type + /// Returns true if sourceType if of type /// - /// An that provides a format context. - /// A that represents the type you want to convert from. + /// An that provides a format context. + /// A that represents the type you want to convert from. /// true if this converter can perform the conversion; otherwise, false. public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - return (sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType); + return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } private static TAttribute GetAttribute(ITypeDescriptorContext context) where TAttribute : UnitAttributeBase { TAttribute attribute = null; - AttributeCollection ua = context?.PropertyDescriptor.Attributes; + var ua = context?.PropertyDescriptor.Attributes; - attribute = (TAttribute)ua?[typeof(TAttribute)]; + attribute = (TAttribute) ua?[typeof(TAttribute)]; if (attribute != null) { - QuantityType expected = default(TQuantity).Type; - QuantityType actual = QuantityType.Undefined; + var expected = default(TQuantity).Type; + var actual = QuantityType.Undefined; if (attribute.UnitType != null) actual = Quantity.From(1, attribute.UnitType).Type; if (actual != QuantityType.Undefined && expected != actual) @@ -161,24 +163,25 @@ private static TAttribute GetAttribute(ITypeDescriptorContext contex } /// - /// Converts the given object, when it is of type to the type of this converter, using the specified context and culture information. + /// Converts the given object, when it is of type to the type of this converter, using the + /// specified context and culture information. /// /// An System.ComponentModel.ITypeDescriptorContext that provides a format context. /// The System.Globalization.CultureInfo to use as the current culture. /// The System.Object to convert. - /// An object. + /// An object. /// The conversion cannot be performed. /// Unit value is not a know unit enum type. public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - string stringValue = value as string; + var stringValue = value as string; object result = null; if (!string.IsNullOrEmpty(stringValue)) { - if (double.TryParse(stringValue, NumberStyles.Any, culture, out double dvalue)) + if (double.TryParse(stringValue, NumberStyles.Any, culture, out var dvalue)) { - DefaultUnitAttribute defaultUnit = GetAttribute(context) ?? new DefaultUnitAttribute(default(TQuantity).Unit); + var defaultUnit = GetAttribute(context) ?? new DefaultUnitAttribute(default(TQuantity).Unit); result = Quantity.From(dvalue, defaultUnit.UnitType); } @@ -187,38 +190,47 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c result = Quantity.Parse(culture, typeof(TQuantity), stringValue); } - ConvertToUnitAttribute convertToUnit = GetAttribute(context); + var convertToUnit = GetAttribute(context); if (convertToUnit != null) { - result = ((IQuantity)result).ToUnit(convertToUnit.UnitType); + result = ((IQuantity) result).ToUnit(convertToUnit.UnitType); } } return result ?? base.ConvertFrom(context, culture, value); } - /// Returns true whether this converter can convert the to string, using the specified context. + /// + /// Returns true whether this converter can convert the to string, using the specified + /// context. + /// /// true if this converter can perform the conversion; otherwise, false. /// An that provides a format context. /// A that represents the type you want to convert to. public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - return (destinationType == typeof(string)) || base.CanConvertTo(context, destinationType); + return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); } - /// Converts the given object to , using the specified context and culture information. + /// + /// Converts the given object to , using the specified context and + /// culture information. + /// /// An that represents the converted value. /// An that provides a format context. - /// A . If null is passed, the current culture is assumed. + /// + /// A . If null is passed, the current culture is + /// assumed. + /// /// The to convert. /// The to convert the parameter to. /// The parameter is null. /// The conversion cannot be performed. public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - IQuantity qvalue = value as IQuantity; + var qvalue = value as IQuantity; object result = null; - DisplayAsUnitAttribute displayAsUnit = GetAttribute(context); + var displayAsUnit = GetAttribute(context); if (destinationType == typeof(string) && qvalue != null && displayAsUnit != null) { diff --git a/UnitsNet/QuantityValue.cs b/UnitsNet/QuantityValue.cs index 66ad890316..8c395fdb08 100644 --- a/UnitsNet/QuantityValue.cs +++ b/UnitsNet/QuantityValue.cs @@ -8,11 +8,16 @@ namespace UnitsNet /// /// A type that supports implicit cast from all .NET numeric types, in order to avoid a large number of overloads /// and binary size for all From(value, unit) factory methods, for each of the 700+ units in the library. - /// stores the value internally with the proper type to preserve the range or precision of the original value: - /// - /// for [byte, short, int, long, float, double] - /// for [decimal] to preserve the 128-bit precision - /// + /// stores the value internally with the proper type to preserve the range or precision of + /// the original value: + /// + /// + /// for [byte, short, int, long, float, double] + /// + /// + /// for [decimal] to preserve the 128-bit precision + /// + /// /// /// /// At the time of this writing, this reduces the number of From(value, unit) overloads to 1/4th: @@ -23,13 +28,13 @@ public struct QuantityValue { /// /// Value assigned when implicitly casting from all numeric types except , since - /// has the greatest range and is 64 bits versus 128 bits for . + /// has the greatest range and is 64 bits versus 128 bits for . /// private readonly double? _value; /// /// Value assigned when implicitly casting from type, since it has a greater precision than - /// and we want to preserve that when constructing quantities that use + /// and we want to preserve that when constructing quantities that use /// as their value type. /// private readonly decimal? _valueDecimal; @@ -52,19 +57,25 @@ private QuantityValue(decimal val) // Prefer double for integer types, since most quantities use that type as of now and // that avoids unnecessary casts back and forth. // If we later change to use decimal more, we should revisit this. - /// Implicit cast from to . + /// Implicit cast from to . public static implicit operator QuantityValue(byte val) => new QuantityValue((double) val); - /// Implicit cast from to . + + /// Implicit cast from to . public static implicit operator QuantityValue(short val) => new QuantityValue((double) val); - /// Implicit cast from to . + + /// Implicit cast from to . public static implicit operator QuantityValue(int val) => new QuantityValue((double) val); - /// Implicit cast from to . + + /// Implicit cast from to . public static implicit operator QuantityValue(long val) => new QuantityValue((double) val); - /// Implicit cast from to . + + /// Implicit cast from to . public static implicit operator QuantityValue(float val) => new QuantityValue(val); // double - /// Implicit cast from to . + + /// Implicit cast from to . public static implicit operator QuantityValue(double val) => new QuantityValue(val); // double - /// Implicit cast from to . + + /// Implicit cast from to . public static implicit operator QuantityValue(decimal val) => new QuantityValue(val); // decimal #pragma warning restore 618 @@ -72,7 +83,7 @@ private QuantityValue(decimal val) #region To double - /// Explicit cast from to . + /// Explicit cast from to . public static explicit operator double(QuantityValue number) { // double -> decimal -> zero (since we can't implement the default struct ctor) @@ -83,7 +94,7 @@ public static explicit operator double(QuantityValue number) #region To decimal - /// Explicit cast from to . + /// Explicit cast from to . public static explicit operator decimal(QuantityValue number) { // decimal -> double -> zero (since we can't implement the default struct ctor) diff --git a/UnitsNet/UnitConverter.cs b/UnitsNet/UnitConverter.cs index b9641f03ce..68a08853c3 100644 --- a/UnitsNet/UnitConverter.cs +++ b/UnitsNet/UnitConverter.cs @@ -13,14 +13,12 @@ namespace UnitsNet using ConversionFunctionLookupKey = ValueTuple; /// - /// /// /// /// public delegate IQuantity ConversionFunction(IQuantity inputValue); /// - /// /// /// /// @@ -34,13 +32,8 @@ public delegate TQuantity ConversionFunction(TQuantity inputValue) [PublicAPI] public sealed partial class UnitConverter { - /// - /// The static instance used by Units.NET to convert between units. Modify this to add/remove conversion functions at runtime, such - /// as adding your own third-party units and quantities to convert between. - /// - public static UnitConverter Default { get; } - - private readonly Dictionary _conversionFunctions = new Dictionary(); + private readonly Dictionary _conversionFunctions = + new Dictionary(); static UnitConverter() { @@ -49,11 +42,18 @@ static UnitConverter() } /// - /// Sets the conversion function from two units of the same quantity type. + /// The static instance used by Units.NET to convert between units. Modify this to add/remove conversion functions at + /// runtime, such + /// as adding your own third-party units and quantities to convert between. /// - /// The type of quantity, must implement . + public static UnitConverter Default { get; } + + /// + /// Sets the conversion function from two units of the same quantity type. + /// + /// The type of quantity, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// The quantity conversion function. public void SetConversionFunction(Enum from, Enum to, ConversionFunction conversionFunction) where TQuantity : IQuantity @@ -64,12 +64,12 @@ public void SetConversionFunction(Enum from, Enum to, ConversionFunct } /// - /// Sets the conversion function from two units of different quantity types. + /// Sets the conversion function from two units of different quantity types. /// - /// From quantity type, must implement . - /// To quantity type, must implement . + /// From quantity type, must implement . + /// To quantity type, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// The quantity conversion function. public void SetConversionFunction(Enum from, Enum to, ConversionFunction conversionFunction) where TQuantityFrom : IQuantity @@ -79,12 +79,12 @@ public void SetConversionFunction(Enum from, Enum to } /// - /// Sets the conversion function from two units of different quantity types. + /// Sets the conversion function from two units of different quantity types. /// - /// From quantity type, must implement . + /// From quantity type, must implement . /// From unit enum value, such as . - /// To quantity type, must implement . - /// To unit enum value, such as . + /// To quantity type, must implement . + /// To unit enum value, such as . /// The quantity conversion function. public void SetConversionFunction(Type fromType, Enum from, Type toType, Enum to, ConversionFunction conversionFunction) { @@ -93,7 +93,7 @@ public void SetConversionFunction(Type fromType, Enum from, Type toType, Enum to } /// - /// Sets the conversion function for a particular conversion function lookup. + /// Sets the conversion function for a particular conversion function lookup. /// /// The lookup key. /// The quantity conversion function. @@ -103,25 +103,28 @@ internal void SetConversionFunction(ConversionFunctionLookupKey lookupKey, Conve } /// - /// Sets the conversion function for a particular conversion function lookup. + /// Sets the conversion function for a particular conversion function lookup. /// - /// The quantity type, must implement . + /// The quantity type, must implement . /// The quantity conversion function lookup key. /// The quantity conversion function. internal void SetConversionFunction(ConversionFunctionLookupKey conversionLookup, ConversionFunction conversionFunction) where TQuantity : IQuantity { - IQuantity TypelessConversionFunction(IQuantity quantity) => conversionFunction((TQuantity) quantity); + IQuantity TypelessConversionFunction(IQuantity quantity) + { + return conversionFunction((TQuantity) quantity); + } _conversionFunctions[conversionLookup] = TypelessConversionFunction; } /// - /// Gets the conversion function from two units of the same quantity type. + /// Gets the conversion function from two units of the same quantity type. /// - /// The quantity type, must implement . + /// The quantity type, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// public ConversionFunction GetConversionFunction(Enum from, Enum to) where TQuantity : IQuantity { @@ -129,12 +132,12 @@ public ConversionFunction GetConversionFunction(Enum from, Enum to) w } /// - /// Gets the conversion function from two units of different quantity types. + /// Gets the conversion function from two units of different quantity types. /// - /// From quantity type, must implement . - /// To quantity type, must implement . + /// From quantity type, must implement . + /// To quantity type, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// public ConversionFunction GetConversionFunction(Enum from, Enum to) where TQuantityFrom : IQuantity @@ -144,12 +147,12 @@ public ConversionFunction GetConversionFunction(Enum } /// - /// Gets the conversion function from two units of different quantity types. + /// Gets the conversion function from two units of different quantity types. /// - /// From quantity type, must implement . + /// From quantity type, must implement . /// From unit enum value, such as . - /// To quantity type, must implement . - /// To unit enum value, such as . + /// To quantity type, must implement . + /// To unit enum value, such as . public ConversionFunction GetConversionFunction(Type fromType, Enum from, Type toType, Enum to) { var conversionLookup = new ConversionFunctionLookupKey(fromType, from, toType, to); @@ -157,27 +160,32 @@ public ConversionFunction GetConversionFunction(Type fromType, Enum from, Type t } /// - /// Gets the conversion function by its lookup key. + /// Gets the conversion function by its lookup key. /// /// internal ConversionFunction GetConversionFunction(ConversionFunctionLookupKey lookupKey) { - IQuantity EchoFunction(IQuantity fromQuantity) => fromQuantity; + IQuantity EchoFunction(IQuantity fromQuantity) + { + return fromQuantity; + } // If from/to units and to quantity types are equal, then return a function that echoes the input quantity // in order to not have to map conversion functions to "self". if (lookupKey.Item1 == lookupKey.Item3 && Equals(lookupKey.Item2, lookupKey.Item4)) + { return EchoFunction; + } return _conversionFunctions[lookupKey]; } /// - /// Gets the conversion function for two units of the same quantity type. + /// Gets the conversion function for two units of the same quantity type. /// - /// The quantity type, must implement . + /// The quantity type, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// The quantity conversion function. /// true if set; otherwise, false. public bool TryGetConversionFunction(Enum from, Enum to, out ConversionFunction conversionFunction) where TQuantity : IQuantity @@ -186,12 +194,12 @@ public bool TryGetConversionFunction(Enum from, Enum to, out Conversi } /// - /// Gets the conversion function for two units of different quantity types. + /// Gets the conversion function for two units of different quantity types. /// - /// From quantity type, must implement . - /// To quantity type, must implement . + /// From quantity type, must implement . + /// To quantity type, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// The quantity conversion function. /// true if set; otherwise, false. public bool TryGetConversionFunction(Enum from, Enum to, out ConversionFunction conversionFunction) @@ -202,12 +210,12 @@ public bool TryGetConversionFunction(Enum from, Enum } /// - /// Try to get the conversion function for two units of the same quantity type. + /// Try to get the conversion function for two units of the same quantity type. /// - /// From quantity type, must implement . + /// From quantity type, must implement . /// From unit enum value, such as . - /// To quantity type, must implement . - /// To unit enum value, such as . + /// To quantity type, must implement . + /// To unit enum value, such as . /// The quantity conversion function. /// true if set; otherwise, false. public bool TryGetConversionFunction(Type fromType, Enum from, Type toType, Enum to, out ConversionFunction conversionFunction) @@ -217,7 +225,6 @@ public bool TryGetConversionFunction(Type fromType, Enum from, Type toType, Enum } /// - /// /// /// /// @@ -252,7 +259,7 @@ public static double Convert(QuantityValue fromValue, Enum fromUnitValue, Enum t public static bool TryConvert(QuantityValue fromValue, Enum fromUnitValue, Enum toUnitValue, out double convertedValue) { convertedValue = 0; - if (!Quantity.TryFrom(fromValue, fromUnitValue, out IQuantity fromQuantity)) return false; + if (!Quantity.TryFrom(fromValue, fromUnitValue, out var fromQuantity)) return false; try { @@ -296,17 +303,19 @@ public static bool TryConvert(QuantityValue fromValue, Enum fromUnitValue, Enum /// More than one unit matches the abbreviation. public static double ConvertByName(QuantityValue fromValue, string quantityName, string fromUnit, string toUnit) { - if (!TryGetUnitType(quantityName, out Type unitType)) + if (!TryGetUnitType(quantityName, out var unitType)) + { throw new UnitNotFoundException($"The unit type for the given quantity was not found: {quantityName}"); + } - if (!TryParseUnit(unitType, fromUnit, out Enum fromUnitValue)) // ex: LengthUnit.Meter + if (!TryParseUnit(unitType, fromUnit, out var fromUnitValue)) // ex: LengthUnit.Meter { var e = new UnitNotFoundException($"Unit not found [{fromUnit}]."); e.Data["unitName"] = fromUnit; throw e; } - if (!TryParseUnit(unitType, toUnit, out Enum toUnitValue)) // ex: LengthUnit.Centimeter + if (!TryParseUnit(unitType, toUnit, out var toUnitValue)) // ex: LengthUnit.Centimeter { var e = new UnitNotFoundException($"Unit not found [{toUnit}]."); e.Data["unitName"] = toUnit; @@ -347,14 +356,20 @@ public static bool TryConvertByName(QuantityValue inputValue, string quantityNam { result = 0d; - if (!TryGetUnitType(quantityName, out Type unitType)) + if (!TryGetUnitType(quantityName, out var unitType)) + { return false; + } - if (!TryParseUnit(unitType, fromUnit, out Enum fromUnitValue)) // ex: LengthUnit.Meter + if (!TryParseUnit(unitType, fromUnit, out var fromUnitValue)) // ex: LengthUnit.Meter + { return false; + } - if (!TryParseUnit(unitType, toUnit, out Enum toUnitValue)) // ex: LengthUnit.Centimeter + if (!TryParseUnit(unitType, toUnit, out var toUnitValue)) // ex: LengthUnit.Centimeter + { return false; + } result = Convert(inputValue, fromUnitValue, toUnitValue); return true; @@ -425,8 +440,10 @@ public static double ConvertByAbbreviation(QuantityValue fromValue, string quant /// More than one unit matches the abbreviation. public static double ConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, string culture) { - if (!TryGetUnitType(quantityName, out Type unitType)) + if (!TryGetUnitType(quantityName, out var unitType)) + { throw new UnitNotFoundException($"The unit type for the given quantity was not found: {quantityName}"); + } var cultureInfo = string.IsNullOrWhiteSpace(culture) ? CultureInfo.CurrentUICulture : new CultureInfo(culture); @@ -502,16 +519,22 @@ public static bool TryConvertByAbbreviation(QuantityValue fromValue, string quan { result = 0d; - if (!TryGetUnitType(quantityName, out Type unitType)) + if (!TryGetUnitType(quantityName, out var unitType)) + { return false; + } var cultureInfo = string.IsNullOrWhiteSpace(culture) ? CultureInfo.CurrentUICulture : new CultureInfo(culture); - if (!UnitParser.Default.TryParse(fromUnitAbbrev, unitType, cultureInfo, out Enum fromUnit)) // ex: ("m", LengthUnit) => LengthUnit.Meter + if (!UnitParser.Default.TryParse(fromUnitAbbrev, unitType, cultureInfo, out var fromUnit)) // ex: ("m", LengthUnit) => LengthUnit.Meter + { return false; + } - if (!UnitParser.Default.TryParse(toUnitAbbrev, unitType, cultureInfo, out Enum toUnit)) // ex:("cm", LengthUnit) => LengthUnit.Centimeter + if (!UnitParser.Default.TryParse(toUnitAbbrev, unitType, cultureInfo, out var toUnit)) // ex:("cm", LengthUnit) => LengthUnit.Centimeter + { return false; + } var fromQuantity = Quantity.From(fromValue, fromUnit); result = fromQuantity.As(toUnit); @@ -533,7 +556,9 @@ private static bool TryParseUnit(Type unitType, string unitName, out Enum unitVa var eNames = Enum.GetNames(unitType); unitName = eNames.FirstOrDefault(x => x.Equals(unitName, StringComparison.OrdinalIgnoreCase)); if (unitName == null) + { return false; + } unitValue = (Enum) Enum.Parse(unitType, unitName); return true; @@ -541,11 +566,10 @@ private static bool TryParseUnit(Type unitType, string unitName, out Enum unitVa private static bool TryGetUnitType(string quantityName, out Type unitType) { - var quantityInfo = Quantity.Infos.FirstOrDefault((info) => info.Name.Equals(quantityName, StringComparison.OrdinalIgnoreCase)); + var quantityInfo = Quantity.Infos.FirstOrDefault(info => info.Name.Equals(quantityName, StringComparison.OrdinalIgnoreCase)); unitType = quantityInfo?.UnitType; return quantityInfo != null; } } } - diff --git a/UnitsNet/UnitFormatter.cs b/UnitsNet/UnitFormatter.cs index 3e1259b718..5594634bc6 100644 --- a/UnitsNet/UnitFormatter.cs +++ b/UnitsNet/UnitFormatter.cs @@ -24,7 +24,7 @@ internal static class UnitFormatter /// A ToString format for the specified value. public static string GetFormat(double value, int significantDigitsAfterRadix) { - double v = Math.Abs(value); + var v = Math.Abs(value); var sigDigitsAfterRadixStr = new string('#', significantDigitsAfterRadix); string format; @@ -38,12 +38,12 @@ public static string GetFormat(double value, int significantDigitsAfterRadix) format = "{0:0." + sigDigitsAfterRadixStr + "e-00} {1}"; } // Values from 1e-3 to 1 use fixed point notation. - else if ((v > 1e-4) && (v < 1)) + else if (v > 1e-4 && v < 1) { format = "{0:g" + significantDigitsAfterRadix + "} {1}"; } // Values between 1 and 1e5 use fixed point notation with digit grouping. - else if ((v >= 1) && (v < 1e6)) + else if (v >= 1 && v < 1e6) { // The comma will be automatically replaced with the correct digit separator if a different culture is used. format = "{0:#,0." + sigDigitsAfterRadixStr + "} {1}"; @@ -74,7 +74,7 @@ private static bool NearlyEqual(double a, double b) public static object[] GetFormatArgs(TUnitType unit, double value, [CanBeNull] IFormatProvider culture, IEnumerable args) where TUnitType : Enum { - string abbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(typeof(TUnitType), Convert.ToInt32(unit), culture); + var abbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(typeof(TUnitType), Convert.ToInt32(unit), culture); return new object[] {value, abbreviation}.Concat(args).ToArray(); } } diff --git a/UnitsNet/UnitInfo.cs b/UnitsNet/UnitInfo.cs index 7f44311779..db73e31fe7 100644 --- a/UnitsNet/UnitInfo.cs +++ b/UnitsNet/UnitInfo.cs @@ -19,10 +19,10 @@ namespace UnitsNet public class UnitInfo { /// - /// Creates an instance of the UnitInfo class. + /// Creates an instance of the UnitInfo class. /// - /// The enum value for this class, for example . - /// The for this unit. + /// The enum value for this class, for example . + /// The for this unit. public UnitInfo([NotNull] Enum value, [NotNull] BaseUnits baseUnits) { Value = value ?? throw new ArgumentNullException(nameof(value)); @@ -31,18 +31,18 @@ public UnitInfo([NotNull] Enum value, [NotNull] BaseUnits baseUnits) } /// - /// The enum value of the unit, such as [, - /// , , ...]. + /// The enum value of the unit, such as [, + /// , , ...]. /// public Enum Value { get; } /// - /// The name of the unit, such as ["Centimeter", "Decimeter", "Meter", ...]. + /// The name of the unit, such as ["Centimeter", "Decimeter", "Meter", ...]. /// public string Name { get; } /// - /// Gets the for this unit. + /// Gets the for this unit. /// public BaseUnits BaseUnits { get; } } @@ -63,7 +63,7 @@ public UnitInfo(TUnit value, BaseUnits baseUnits) : base(value, baseUnits) Value = value; } - /// + /// public new TUnit Value { get; } } } diff --git a/UnitsNet/UnitMath.cs b/UnitsNet/UnitMath.cs index 2d1eec758a..a9b03aa90c 100644 --- a/UnitsNet/UnitMath.cs +++ b/UnitsNet/UnitMath.cs @@ -1,4 +1,7 @@ -using System; +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; using System.Collections.Generic; using System.Linq; diff --git a/UnitsNet/UnitSystem.cs b/UnitsNet/UnitSystem.cs index f55821b7ff..fa42f39346 100644 --- a/UnitsNet/UnitSystem.cs +++ b/UnitsNet/UnitSystem.cs @@ -8,63 +8,85 @@ namespace UnitsNet { /// /// A unit system defined by a combination of base units. - /// This is typically used to define the "working units" for consistently creating and presenting quantities in the selected base units, - /// such as to use SI base units such as meters, kilograms and seconds. + /// This is typically used to define the "working units" for consistently creating and presenting quantities in the + /// selected base units, + /// such as to use SI base units such as meters, kilograms and seconds. /// public sealed class UnitSystem : IEquatable { + private static readonly BaseUnits SIBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + /// - /// Creates an instance of a unit system with the specified base units. + /// Creates an instance of a unit system with the specified base units. /// /// The base units for the unit system. public UnitSystem(BaseUnits baseUnits) { - if(baseUnits is null) + if (baseUnits is null) + { throw new ArgumentNullException(nameof(baseUnits)); + } - if(!baseUnits.IsFullyDefined) + if (!baseUnits.IsFullyDefined) + { throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); + } BaseUnits = baseUnits; } + /// + /// The base units of this unit system. + /// + public BaseUnits BaseUnits { get; } + + /// + /// Gets the SI unit system. + /// + public static UnitSystem SI { get; } = new UnitSystem(SIBaseUnits); + /// - public override bool Equals(object obj) + public bool Equals(UnitSystem other) { - if(obj is null || !(obj is UnitSystem)) + if (other is null) + { return false; + } - return Equals((UnitSystem)obj); + return BaseUnits.Equals(other.BaseUnits); } /// - public bool Equals(UnitSystem other) + public override bool Equals(object obj) { - if(other is null) + if (obj is null || !(obj is UnitSystem)) + { return false; + } - return BaseUnits.Equals(other.BaseUnits); + return Equals((UnitSystem) obj); } /// - /// Checks if this instance is equal to another. + /// Checks if this instance is equal to another. /// /// The left instance. /// The right instance. /// True if equal, otherwise false. - /// + /// public static bool operator ==(UnitSystem left, UnitSystem right) { return left is null ? right is null : left.Equals(right); } /// - /// Checks if this instance is equal to another. + /// Checks if this instance is equal to another. /// /// The left instance. /// The right instance. /// True if equal, otherwise false. - /// + /// public static bool operator !=(UnitSystem left, UnitSystem right) { return !(left == right); @@ -75,18 +97,5 @@ public override int GetHashCode() { return new {BaseUnits}.GetHashCode(); } - - /// - /// The base units of this unit system. - /// - public BaseUnits BaseUnits{ get; } - - private static readonly BaseUnits SIBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - - /// - /// Gets the SI unit system. - /// - public static UnitSystem SI { get; } = new UnitSystem(SIBaseUnits); } } From ca7caf143ef58c38a1861d2cab3fbb95cc614365 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 11 Dec 2019 11:48:01 -0600 Subject: [PATCH 20/24] Revert "Renamed files added to CustomCode, ran ReSharper rules on solution to meet code style requirements." This reverts commit ffa1d057c7f68511e88bb4196015701a35d5bca6. --- CodeGen/Generators/GeneratorBase.cs | 6 +- CodeGen/Generators/QuantityJsonFilesParser.cs | 14 +- .../IQuantityTestClassGenerator.cs | 58 +- .../UnitsNetGen/QuantityGenerator.cs | 44 +- .../UnitsNetGen/QuantityTypeGenerator.cs | 6 - .../UnitsNetGen/StaticQuantityGenerator.cs | 3 - .../UnitAbbreviationsCacheGenerator.cs | 3 - .../UnitsNetGen/UnitConverterGenerator.cs | 21 +- .../UnitsNetGen/UnitTestBaseClassGenerator.cs | 84 +-- .../UnitsNetGen/UnitTestStubGenerator.cs | 3 - .../UnitsNetGen/UnitTypeGenerator.cs | 9 +- .../UnitsNetWrcGen/QuantityGenerator.cs | 65 +- .../UnitsNetWrcGen/QuantityTypeGenerator.cs | 6 - .../UnitsNetWrcGen/StaticQuantityGenerator.cs | 33 +- .../UnitAbbreviationsCacheGenerator.cs | 3 - .../UnitsNetWrcGen/UnitTypeGenerator.cs | 9 +- CodeGen/Helpers/MyTextWriter.cs | 15 +- CodeGen/Helpers/StringExtensions.cs | 4 +- CodeGen/JsonTypes/BaseDimensions.cs | 6 - CodeGen/JsonTypes/BaseUnits.cs | 6 - CodeGen/JsonTypes/Prefix.cs | 5 +- CodeGen/JsonTypes/Quantity.cs | 1 + CodeGen/PrefixInfo.cs | 39 +- CodeGen/Program.cs | 7 +- Common/UnitDefinitions/Acceleration.json | 19 +- Common/UnitDefinitions/AmountOfSubstance.json | 11 +- Common/UnitDefinitions/AmplitudeRatio.json | 8 +- Common/UnitDefinitions/Angle.json | 27 +- Common/UnitDefinitions/ApparentEnergy.json | 7 +- Common/UnitDefinitions/ApparentPower.json | 7 +- Common/UnitDefinitions/Area.json | 51 +- Common/UnitDefinitions/AreaDensity.json | 2 +- .../UnitDefinitions/AreaMomentOfInertia.json | 12 +- Common/UnitDefinitions/BitRate.json | 11 +- .../BrakeSpecificFuelConsumption.json | 9 +- Common/UnitDefinitions/Capacitance.json | 4 +- .../CoefficientOfThermalExpansion.json | 6 +- Common/UnitDefinitions/Density.json | 50 +- Common/UnitDefinitions/Duration.json | 35 +- Common/UnitDefinitions/DynamicViscosity.json | 19 +- .../UnitDefinitions/ElectricAdmittance.json | 7 +- Common/UnitDefinitions/ElectricCharge.json | 9 +- .../ElectricChargeDensity.json | 2 +- .../UnitDefinitions/ElectricConductance.json | 7 +- .../UnitDefinitions/ElectricConductivity.json | 9 +- Common/UnitDefinitions/ElectricCurrent.json | 7 +- .../ElectricCurrentDensity.json | 6 +- .../ElectricCurrentGradient.json | 2 +- Common/UnitDefinitions/ElectricField.json | 5 +- .../UnitDefinitions/ElectricInductance.json | 4 +- Common/UnitDefinitions/ElectricPotential.json | 9 +- .../UnitDefinitions/ElectricPotentialAc.json | 4 +- .../UnitDefinitions/ElectricPotentialDc.json | 4 +- .../UnitDefinitions/ElectricResistance.json | 7 +- .../UnitDefinitions/ElectricResistivity.json | 11 +- .../ElectricSurfaceChargeDensity.json | 9 +- Common/UnitDefinitions/Energy.json | 47 +- Common/UnitDefinitions/Entropy.json | 17 +- Common/UnitDefinitions/Force.json | 37 +- Common/UnitDefinitions/ForceChangeRate.json | 11 +- Common/UnitDefinitions/ForcePerLength.json | 14 +- Common/UnitDefinitions/Frequency.json | 14 +- Common/UnitDefinitions/FuelEfficiency.json | 86 +-- Common/UnitDefinitions/HeatFlux.json | 26 +- .../HeatTransferCoefficient.json | 9 +- Common/UnitDefinitions/Illuminance.json | 4 +- Common/UnitDefinitions/Information.json | 11 +- Common/UnitDefinitions/Irradiance.json | 8 +- Common/UnitDefinitions/Irradiation.json | 17 +- .../UnitDefinitions/KinematicViscosity.json | 15 +- Common/UnitDefinitions/LapseRate.json | 5 +- Common/UnitDefinitions/Length.json | 72 +- Common/UnitDefinitions/Level.json | 7 +- Common/UnitDefinitions/LinearDensity.json | 9 +- Common/UnitDefinitions/Luminosity.json | 9 +- Common/UnitDefinitions/LuminousFlux.json | 2 +- Common/UnitDefinitions/LuminousIntensity.json | 5 +- Common/UnitDefinitions/MagneticField.json | 7 +- Common/UnitDefinitions/MagneticFlux.json | 5 +- Common/UnitDefinitions/Magnetization.json | 5 +- Common/UnitDefinitions/Mass.json | 74 +- Common/UnitDefinitions/MassConcentration.json | 51 +- Common/UnitDefinitions/MassFlow.json | 45 +- Common/UnitDefinitions/MassFlux.json | 4 +- Common/UnitDefinitions/MassFraction.json | 22 +- .../UnitDefinitions/MassMomentOfInertia.json | 40 +- Common/UnitDefinitions/MolarEnergy.json | 6 +- Common/UnitDefinitions/MolarEntropy.json | 6 +- Common/UnitDefinitions/MolarMass.json | 17 +- Common/UnitDefinitions/Molarity.json | 11 +- Common/UnitDefinitions/Permeability.json | 5 +- Common/UnitDefinitions/Permittivity.json | 5 +- Common/UnitDefinitions/Power.json | 25 +- Common/UnitDefinitions/PowerDensity.json | 16 +- Common/UnitDefinitions/PowerRatio.json | 4 +- Common/UnitDefinitions/Pressure.json | 87 ++- .../UnitDefinitions/PressureChangeRate.json | 21 +- Common/UnitDefinitions/Ratio.json | 15 +- Common/UnitDefinitions/RatioChangeRate.json | 5 +- Common/UnitDefinitions/ReactiveEnergy.json | 7 +- Common/UnitDefinitions/ReactivePower.json | 7 +- .../RotationalAcceleration.json | 8 +- Common/UnitDefinitions/RotationalSpeed.json | 25 +- .../UnitDefinitions/RotationalStiffness.json | 4 +- .../RotationalStiffnessPerLength.json | 4 +- Common/UnitDefinitions/SolidAngle.json | 5 +- Common/UnitDefinitions/SpecificEnergy.json | 15 +- Common/UnitDefinitions/SpecificEntropy.json | 17 +- Common/UnitDefinitions/SpecificVolume.json | 11 +- Common/UnitDefinitions/SpecificWeight.json | 37 +- Common/UnitDefinitions/Speed.json | 43 +- Common/UnitDefinitions/Temperature.json | 21 +- .../TemperatureChangeRate.json | 9 +- Common/UnitDefinitions/TemperatureDelta.json | 16 +- .../UnitDefinitions/ThermalConductivity.json | 4 +- Common/UnitDefinitions/ThermalResistance.json | 11 +- Common/UnitDefinitions/Torque.json | 39 +- Common/UnitDefinitions/TorquePerLength.json | 36 +- Common/UnitDefinitions/VitaminA.json | 2 +- Common/UnitDefinitions/Volume.json | 97 ++- .../UnitDefinitions/VolumeConcentration.json | 29 +- Common/UnitDefinitions/VolumeFlow.json | 91 ++- Common/UnitDefinitions/VolumePerLength.json | 8 +- UnitsNet.Benchmark/Program.cs | 11 +- .../UnitsNetJsonConverterTests.cs | 343 +++++---- .../UnitsNetJsonConverterTests.cs | 339 +++++---- .../Internal/ReflectionHelper.cs | 17 +- .../UnitsNetJsonConverter.cs | 69 +- UnitsNet.Tests/AssemblyAttributeTests.cs | 20 +- UnitsNet.Tests/AssertEx.cs | 23 +- UnitsNet.Tests/BaseDimensionsTests.cs | 693 +++++++++--------- UnitsNet.Tests/BaseUnitsTests.cs | 152 ++-- .../CustomCode/AccelerationTests.cs | 2 +- .../CustomCode/AmplitudeRatioTests.cs | 22 +- UnitsNet.Tests/CustomCode/AngleTests.cs | 4 +- UnitsNet.Tests/CustomCode/AreaTests.cs | 53 +- .../BrakeSpecificFuelConsumptionTests.cs | 15 +- UnitsNet.Tests/CustomCode/DensityTests.cs | 32 +- UnitsNet.Tests/CustomCode/DurationTests.cs | 164 ++--- .../CustomCode/DynamicViscosityTests.cs | 3 +- .../CustomCode/ElectricCurrentTests.cs | 2 +- .../CustomCode/ElectricPotentialTests.cs | 4 +- .../CustomCode/ElectricResistanceTests.cs | 2 +- UnitsNet.Tests/CustomCode/EnergyTests.cs | 12 +- UnitsNet.Tests/CustomCode/ForceTests.cs | 40 +- UnitsNet.Tests/CustomCode/FrequencyTests.cs | 2 +- UnitsNet.Tests/CustomCode/IQuantityTests.cs | 24 +- UnitsNet.Tests/CustomCode/InformationTests.cs | 48 +- .../CustomCode/KinematicViscosityTests.cs | 24 +- UnitsNet.Tests/CustomCode/KnownQuantities.cs | 5 +- .../CustomCode/LengthTests.FeetInches.cs | 38 +- UnitsNet.Tests/CustomCode/LengthTests.cs | 102 +-- UnitsNet.Tests/CustomCode/LevelTests.cs | 4 +- UnitsNet.Tests/CustomCode/MassFlowTests.cs | 58 +- UnitsNet.Tests/CustomCode/MassTests.cs | 44 +- UnitsNet.Tests/CustomCode/ParseTests.cs | 42 +- UnitsNet.Tests/CustomCode/PowerRatioTests.cs | 20 +- UnitsNet.Tests/CustomCode/PowerTests.cs | 56 +- .../CustomCode/PressureChangeRateTests.cs | 2 +- .../CustomCode/RotationalSpeedTests.cs | 8 +- .../CustomCode/SpecificEnergyTests.cs | 28 +- .../CustomCode/SpecificWeightTests.cs | 14 +- UnitsNet.Tests/CustomCode/SpeedTests.cs | 42 +- UnitsNet.Tests/CustomCode/StonePoundsTests.cs | 40 +- .../CustomCode/TemperatureChangeRateTests.cs | 2 +- UnitsNet.Tests/CustomCode/TemperatureTests.cs | 111 +-- UnitsNet.Tests/CustomCode/TorqueTests.cs | 4 +- UnitsNet.Tests/CustomCode/VolumeTests.cs | 44 +- UnitsNet.Tests/CustomQuantities/HowMuch.cs | 12 +- .../CustomQuantities/HowMuchUnit.cs | 5 +- UnitsNet.Tests/DecimalOverloadTests.cs | 12 +- UnitsNet.Tests/DummyIQuantity.cs | 7 +- UnitsNet.Tests/EnumUtils.cs | 2 +- UnitsNet.Tests/GeneratedQuantityCodeTests.cs | 11 +- .../Helpers/TypeDescriptorContext.cs | 57 +- UnitsNet.Tests/IntOverloadTests.cs | 4 +- UnitsNet.Tests/InterUnitConversionTests.cs | 8 +- UnitsNet.Tests/LongOverloadTests.cs | 4 +- UnitsNet.Tests/QuantityIConvertibleTests.cs | 13 +- UnitsNet.Tests/QuantityIFormattableTests.cs | 48 +- UnitsNet.Tests/QuantityInfoTest.cs | 167 ++--- UnitsNet.Tests/QuantityParserTests.cs | 5 +- UnitsNet.Tests/QuantityTest.cs | 78 +- UnitsNet.Tests/QuantityTests.Ctor.cs | 203 +++-- UnitsNet.Tests/QuantityTests.ToString.cs | 82 +-- UnitsNet.Tests/QuantityTests.cs | 44 +- UnitsNet.Tests/QuantityTypeConverterTest.cs | 263 +++---- .../UnitAbbreviationsCacheFixture.cs | 5 +- UnitsNet.Tests/UnitAbbreviationsCacheTests.cs | 133 ++-- UnitsNet.Tests/UnitConverterTest.cs | 225 +++--- UnitsNet.Tests/UnitMathTests.cs | 71 +- UnitsNet.Tests/UnitParserTests.cs | 92 +-- UnitsNet.Tests/UnitSystemTests.cs | 85 +-- UnitsNet/AssemblyInfo.cs | 5 +- UnitsNet/BaseDimensions.cs | 165 ++--- UnitsNet/BaseUnits.cs | 189 +++-- UnitsNet/Comparison.cs | 6 - UnitsNet/ComparisonType.cs | 6 +- UnitsNet/CustomCode/GlobalConfiguration.cs | 2 +- .../Quantities/Acceleration.extra.cs | 6 +- .../Quantities/AmountOfSubstance.extra.cs | 22 +- .../Quantities/AmplitudeRatio.extra.cs | 8 +- UnitsNet/CustomCode/Quantities/Angle.extra.cs | 2 +- UnitsNet/CustomCode/Quantities/Area.extra.cs | 6 +- .../Quantities/AreaMomentOfInertia.extra.cs | 4 +- .../BrakeSpecificFuelConsumption.extra.cs | 15 +- .../CustomCode/Quantities/Density.extra.cs | 18 +- .../CustomCode/Quantities/Duration.extra.cs | 37 +- .../Quantities/DynamicViscosity.extra.cs | 2 +- .../Quantities/ElectricCurrent.extra.cs | 5 +- .../Quantities/ElectricPotential.extra.cs | 13 +- .../Quantities/ElectricResistance.extra.cs | 5 +- UnitsNet/CustomCode/Quantities/Force.extra.cs | 18 +- .../Quantities/ForcePerLength.extra.cs | 6 +- .../CustomCode/Quantities/HeatFlux.extra.cs | 2 +- .../Quantities/KinematicViscosity.extra.cs | 12 +- .../CustomCode/Quantities/LapseRate.extra.cs | 6 +- .../CustomCode/Quantities/Length.extra.cs | 98 ++- UnitsNet/CustomCode/Quantities/Level.extra.cs | 9 +- UnitsNet/CustomCode/Quantities/Mass.extra.cs | 36 +- .../Quantities/MassConcentration.extra.cs | 23 +- .../CustomCode/Quantities/MassFlow.extra.cs | 22 +- .../CustomCode/Quantities/MassFlux.extra.cs | 6 +- .../Quantities/MassFraction.extra.cs | 22 +- .../CustomCode/Quantities/Molarity.extra.cs | 37 +- UnitsNet/CustomCode/Quantities/Power.extra.cs | 26 +- .../CustomCode/Quantities/PowerRatio.extra.cs | 3 +- .../CustomCode/Quantities/Pressure.extra.cs | 14 +- .../Quantities/RotationalSpeed.extra.cs | 8 +- .../Quantities/RotationalStiffness.extra.cs | 12 +- .../RotationalStiffnessPerLength.extra.cs | 6 +- .../Quantities/SpecificEnergy.extra.cs | 16 +- .../Quantities/SpecificVolume.extra.cs | 4 +- .../Quantities/SpecificWeight.extra.cs | 16 +- UnitsNet/CustomCode/Quantities/Speed.extra.cs | 20 +- .../Quantities/Temperature.extra.cs | 4 +- .../Quantities/TemperatureDelta.extra.cs | 6 +- .../CustomCode/Quantities/Torque.extra.cs | 8 +- .../CustomCode/Quantities/Volume.extra.cs | 10 +- .../Quantities/VolumeConcentration.extra.cs | 33 +- .../CustomCode/Quantities/VolumeFlow.extra.cs | 12 +- UnitsNet/CustomCode/Quantity.cs | 44 +- UnitsNet/CustomCode/QuantityParser.cs | 37 +- UnitsNet/CustomCode/UnitAbbreviationsCache.cs | 203 ++--- UnitsNet/CustomCode/UnitParser.cs | 92 +-- .../CustomCode/UnitValueAbbreviationLookup.cs | 33 +- ...PressureReference.cs => PressureUnit.g.cs} | 0 ...ferencePressure.cs => Pressure.Wrapper.cs} | 30 +- UnitsNet/IQuantity.cs | 89 +-- .../ReflectionBridgeExtensions.cs | 10 +- UnitsNet/QuantityFormatter.cs | 57 +- UnitsNet/QuantityInfo.cs | 68 +- UnitsNet/QuantityTypeConverter.cs | 152 ++-- UnitsNet/QuantityValue.cs | 43 +- UnitsNet/UnitConverter.cs | 148 ++-- UnitsNet/UnitFormatter.cs | 8 +- UnitsNet/UnitInfo.cs | 16 +- UnitsNet/UnitMath.cs | 5 +- UnitsNet/UnitSystem.cs | 65 +- 259 files changed, 4155 insertions(+), 4653 deletions(-) rename UnitsNet/CustomCode/Units/{PressureReference.cs => PressureUnit.g.cs} (100%) rename UnitsNet/CustomCode/Wrappers/{ReferencePressure.cs => Pressure.Wrapper.cs} (97%) diff --git a/CodeGen/Generators/GeneratorBase.cs b/CodeGen/Generators/GeneratorBase.cs index 4f16c11375..53c9a23f7f 100644 --- a/CodeGen/Generators/GeneratorBase.cs +++ b/CodeGen/Generators/GeneratorBase.cs @@ -7,6 +7,9 @@ namespace CodeGen.Generators { internal abstract class GeneratorBase { + protected readonly MyTextWriter Writer = new MyTextWriter(); + public abstract string Generate(); + public const string GeneratedFileHeader = @"//------------------------------------------------------------------------------ // // This code was generated by \generate-code.bat. @@ -26,8 +29,5 @@ internal abstract class GeneratorBase // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. "; - - protected readonly MyTextWriter Writer = new MyTextWriter(); - public abstract string Generate(); } } diff --git a/CodeGen/Generators/QuantityJsonFilesParser.cs b/CodeGen/Generators/QuantityJsonFilesParser.cs index 5cd40388f0..3ab95e8d4b 100644 --- a/CodeGen/Generators/QuantityJsonFilesParser.cs +++ b/CodeGen/Generators/QuantityJsonFilesParser.cs @@ -110,9 +110,13 @@ private static Localization[] GetLocalizationForPrefixUnit(IEnumerable { - if (loc.TryGetAbbreviationsForPrefix(prefixInfo.Prefix, out var unitAbbreviationsForPrefix)) + if (loc.TryGetAbbreviationsForPrefix(prefixInfo.Prefix, out string[] unitAbbreviationsForPrefix)) { - return new Localization {Culture = loc.Culture, Abbreviations = unitAbbreviationsForPrefix}; + return new Localization + { + Culture = loc.Culture, + Abbreviations = unitAbbreviationsForPrefix + }; } // No prefix unit abbreviations are specified, so fall back to prepending the default SI prefix to each unit abbreviation: @@ -120,7 +124,11 @@ private static Localization[] GetLocalizationForPrefixUnit(IEnumerable $"{prefix}{unitAbbreviation}").ToArray(); - return new Localization {Culture = loc.Culture, Abbreviations = unitAbbreviationsForPrefix}; + return new Localization + { + Culture = loc.Culture, + Abbreviations = unitAbbreviationsForPrefix + }; }).ToArray(); } } diff --git a/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs index f36c1acd31..5469bfc504 100644 --- a/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/IQuantityTestClassGenerator.cs @@ -1,6 +1,7 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using System; using System.Linq; using CodeGen.JsonTypes; @@ -18,23 +19,23 @@ public IQuantityTestClassGenerator(Quantity[] quantities) public override string Generate() { Writer.WL(GeneratedFileHeader); - Writer.WL(@" + Writer.WL($@" using System; using UnitsNet.Units; using Xunit; namespace UnitsNet.Tests -{ +{{ public partial class IQuantityTests - { + {{ [Fact] public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() - { + {{ void Assertion(int expectedValue, Enum expectedUnit, IQuantity quantity) - { + {{ Assert.Equal(expectedUnit, quantity.Unit); Assert.Equal(expectedValue, quantity.Value); - } + }} "); foreach (var quantity in _quantities) { @@ -46,53 +47,40 @@ void Assertion(int expectedValue, Enum expectedUnit, IQuantity quantity) Writer.WL($@" Assertion(3, {unitEnumNameAndValue}, Quantity.From(3, {unitEnumNameAndValue}));"); } - - Writer.WL(@" - } + Writer.WL($@" + }} [Fact] public void QuantityInfo_IsSameAsStaticInfoProperty() - { + {{ void Assertion(QuantityInfo expected, IQuantity quantity) => Assert.Same(expected, quantity.QuantityInfo); "); - foreach (var quantity in _quantities) - { - Writer.WL($@" + foreach (var quantity in _quantities) Writer.WL($@" Assertion({quantity.Name}.Info, {quantity.Name}.Zero);"); - } - - Writer.WL(@" - } + Writer.WL($@" + }} [Fact] public void Type_EqualsStaticQuantityTypeProperty() - { + {{ void Assertion(QuantityType expected, IQuantity quantity) => Assert.Equal(expected, quantity.Type); "); - foreach (var quantity in _quantities) - { - Writer.WL($@" + foreach (var quantity in _quantities) Writer.WL($@" Assertion({quantity.Name}.QuantityType, {quantity.Name}.Zero);"); - } - - Writer.WL(@" - } + Writer.WL($@" + }} [Fact] public void Dimensions_IsSameAsStaticBaseDimensions() - { + {{ void Assertion(BaseDimensions expected, IQuantity quantity) => Assert.Equal(expected, quantity.Dimensions); "); - foreach (var quantity in _quantities) - { - Writer.WL($@" + foreach (var quantity in _quantities) Writer.WL($@" Assertion({quantity.Name}.BaseDimensions, {quantity.Name}.Zero);"); - } - - Writer.WL(@" - } - } -}"); + Writer.WL($@" + }} + }} +}}"); return Writer.ToString(); } diff --git a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs index 3ac24e78e8..caff760f4a 100644 --- a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs @@ -10,12 +10,12 @@ namespace CodeGen.Generators.UnitsNetGen { internal class QuantityGenerator : GeneratorBase { - private readonly Unit _baseUnit; + private readonly Quantity _quantity; private readonly bool _isDimensionless; - private readonly Quantity _quantity; private readonly string _unitEnumName; private readonly string _valueType; + private readonly Unit _baseUnit; public QuantityGenerator(Quantity quantity) { @@ -28,15 +28,16 @@ public QuantityGenerator(Quantity quantity) _valueType = quantity.BaseType; _unitEnumName = $"{quantity.Name}Unit"; - var baseDimensions = quantity.BaseDimensions; + BaseDimensions baseDimensions = quantity.BaseDimensions; _isDimensionless = baseDimensions == null || - baseDimensions.L == 0 && - baseDimensions.M == 0 && - baseDimensions.T == 0 && - baseDimensions.I == 0 && - baseDimensions.Θ == 0 && - baseDimensions.N == 0 && - baseDimensions.J == 0; + baseDimensions.L == 0 && + baseDimensions.M == 0 && + baseDimensions.T == 0 && + baseDimensions.I == 0 && + baseDimensions.Θ == 0 && + baseDimensions.N == 0 && + baseDimensions.J == 0; + } public override string Generate() @@ -93,9 +94,9 @@ public partial struct {_quantity.Name} : IQuantity<{_unitEnumName}>, IEquatable< GenerateToString(); GenerateIConvertibleMethods(); - Writer.WL(@" - } -}"); + Writer.WL($@" + }} +}}"); return Writer.ToString(); } @@ -130,7 +131,8 @@ private void GenerateStaticConstructor() var baseUnitsCtorArgs = string.Join(", ", new[] { - baseUnits.L != null ? $"length: LengthUnit.{baseUnits.L}" : null, baseUnits.M != null ? $"mass: MassUnit.{baseUnits.M}" : null, + baseUnits.L != null ? $"length: LengthUnit.{baseUnits.L}" : null, + baseUnits.M != null ? $"mass: MassUnit.{baseUnits.M}" : null, baseUnits.T != null ? $"time: DurationUnit.{baseUnits.T}" : null, baseUnits.I != null ? $"current: ElectricCurrentUnit.{baseUnits.I}" : null, baseUnits.Θ != null ? $"temperature: TemperatureUnit.{baseUnits.Θ}" : null, @@ -261,11 +263,9 @@ private void GenerateProperties() // Need to provide explicit interface implementation for decimal quantities like Information if (_quantity.BaseType != "double") - { Writer.WL(@" double IQuantity.Value => (double) _value; "); - } Writer.WL($@" Enum IQuantity.Unit => Unit; @@ -538,9 +538,7 @@ public static bool TryParseUnit(string str, IFormatProvider provider, out {_unit private void GenerateArithmeticOperators() { if (!_quantity.GenerateArithmetic) - { return; - } // Logarithmic units required different arithmetic if (_quantity.Logarithmic) @@ -1030,7 +1028,7 @@ public string ToString(string format, IFormatProvider formatProvider) private void GenerateIConvertibleMethods() { - Writer.WL($@" + Writer.WL($@" #region IConvertible Methods TypeCode IConvertible.GetTypeCode() @@ -1130,15 +1128,15 @@ ulong IConvertible.ToUInt64(IFormatProvider provider) #endregion"); } - /// + /// internal static string GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText); - /// + /// internal static string GetObsoleteAttributeOrNull(Unit unit) => GetObsoleteAttributeOrNull(unit.ObsoleteText); /// - /// Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string - /// It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats + /// Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string + /// It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats /// private static string GetObsoleteAttributeOrNull(string obsoleteText) => string.IsNullOrWhiteSpace(obsoleteText) ? null diff --git a/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs b/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs index a49f858f9c..b105c5cbc6 100644 --- a/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/QuantityTypeGenerator.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using CodeGen.JsonTypes; namespace CodeGen.Generators.UnitsNetGen @@ -33,11 +30,8 @@ public enum QuantityType #pragma warning disable CS1591 Undefined = 0,"); foreach (var quantity in _quantities) - { Writer.WL($@" {quantity.Name},"); - } - Writer.WL(@" // Missing XML comment for public type or member #pragma warning restore CS1591 diff --git a/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs index e21e45e2c0..25d9143e49 100644 --- a/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using CodeGen.Helpers; using CodeGen.JsonTypes; diff --git a/CodeGen/Generators/UnitsNetGen/UnitAbbreviationsCacheGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitAbbreviationsCacheGenerator.cs index 269a128a06..26189a0172 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitAbbreviationsCacheGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitAbbreviationsCacheGenerator.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using System.Linq; using CodeGen.JsonTypes; diff --git a/CodeGen/Generators/UnitsNetGen/UnitConverterGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitConverterGenerator.cs index 78c53e9a12..09047b06e9 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitConverterGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitConverterGenerator.cs @@ -1,6 +1,7 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using CodeGen.Helpers; using CodeGen.JsonTypes; namespace CodeGen.Generators.UnitsNetGen @@ -17,24 +18,24 @@ public UnitConverterGenerator(Quantity[] quantities) public override string Generate() { Writer.WL(GeneratedFileHeader); - Writer.WL(@" + Writer.WL($@" using UnitsNet.Units; // ReSharper disable RedundantCommaInArrayInitializer // ReSharper disable once CheckNamespace namespace UnitsNet -{ +{{ public sealed partial class UnitConverter - { + {{ /// /// Registers the default conversion functions in the given instance. /// /// The to register the default conversion functions in. public static void RegisterDefaultConversions(UnitConverter unitConverter) - {"); - foreach (var quantity in _quantities) - foreach (var unit in quantity.Units) + {{"); + foreach (Quantity quantity in _quantities) + foreach (Unit unit in quantity.Units) { Writer.WL(quantity.BaseUnit == unit.SingularName ? $@" @@ -44,10 +45,10 @@ public static void RegisterDefaultConversions(UnitConverter unitConverter) unitConverter.SetConversionFunction<{quantity.Name}>({quantity.Name}Unit.{unit.SingularName}, {quantity.Name}.BaseUnit, q => q.ToBaseUnit());"); } - Writer.WL(@" - } - } -}"); + Writer.WL($@" + }} + }} +}}"); return Writer.ToString(); } diff --git a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs index 2ffa35f596..41f6edb63f 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using System; using System.Linq; using CodeGen.JsonTypes; @@ -9,8 +6,8 @@ namespace CodeGen.Generators.UnitsNetGen { internal class UnitTestBaseClassGenerator : GeneratorBase { - private readonly Unit _baseUnit; private readonly Quantity _quantity; + private readonly Unit _baseUnit; private readonly string _unitEnumName; public UnitTestBaseClassGenerator(Quantity quantity) @@ -45,22 +42,14 @@ namespace UnitsNet.Tests // ReSharper disable once PartialTypeWithSinglePart public abstract partial class {_quantity.Name}TestsBase {{"); - foreach (var unit in _quantity.Units) - { - Writer.WL($@" + foreach (var unit in _quantity.Units) Writer.WL($@" protected abstract double {unit.PluralName}InOne{_baseUnit.SingularName} {{ get; }}"); - } - - Writer.WL(); - Writer.WL(@" -// ReSharper disable VirtualMemberNeverOverriden.Global"); - foreach (var unit in _quantity.Units) - { - Writer.WL($@" - protected virtual double {unit.PluralName}Tolerance {{ get {{ return 1e-5; }} }}"); - } + Writer.WL(""); Writer.WL($@" +// ReSharper disable VirtualMemberNeverOverriden.Global"); + foreach (var unit in _quantity.Units) Writer.WL($@" + protected virtual double {unit.PluralName}Tolerance {{ get {{ return 1e-5; }} }}"); Writer.WL($@" // ReSharper restore VirtualMemberNeverOverriden.Global [Fact] @@ -69,9 +58,7 @@ public void Ctor_WithUndefinedUnit_ThrowsArgumentException() Assert.Throws(() => new {_quantity.Name}(({_quantity.BaseType})0.0, {_unitEnumName}.Undefined)); }} "); - if (_quantity.BaseType == "double") - { - Writer.WL($@" + if (_quantity.BaseType == "double") Writer.WL($@" [Fact] public void Ctor_WithInfinityValue_ThrowsArgumentException() {{ @@ -84,40 +71,27 @@ public void Ctor_WithNaNValue_ThrowsArgumentException() {{ Assert.Throws(() => new {_quantity.Name}(double.NaN, {_unitEnumName}.{_baseUnit.SingularName})); }} -"); - } - - Writer.WL($@" +"); Writer.WL($@" [Fact] public void {_baseUnit.SingularName}To{_quantity.Name}Units() {{ {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);"); - foreach (var unit in _quantity.Units) - { - Writer.WL($@" + foreach (var unit in _quantity.Units) Writer.WL($@" AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, {baseUnitVariableName}.{unit.PluralName}, {unit.PluralName}Tolerance);"); - } - - Writer.WL(@" - } + Writer.WL($@" + }} [Fact] public void FromValueAndUnit() - {"); - foreach (var unit in _quantity.Units) - { - Writer.WL($@" + {{"); + foreach (var unit in _quantity.Units) Writer.WL($@" AssertEx.EqualTolerance(1, {_quantity.Name}.From(1, {_unitEnumName}.{unit.SingularName}).{unit.PluralName}, {unit.PluralName}Tolerance);"); - } - - Writer.WL(@" - } + Writer.WL($@" + }} "); - if (_quantity.BaseType == "double") - { - Writer.WL($@" + if (_quantity.BaseType == "double") Writer.WL($@" [Fact] public void From{_baseUnit.PluralName}_WithInfinityValue_ThrowsArgumentException() {{ @@ -130,21 +104,14 @@ public void FromValueAndUnit() {{ Assert.Throws(() => {_quantity.Name}.From{_baseUnit.PluralName}(double.NaN)); }} -"); - } - - Writer.WL($@" +"); Writer.WL($@" [Fact] public void As() {{ var {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);"); - foreach (var unit in _quantity.Units) - { - Writer.WL($@" + foreach (var unit in _quantity.Units) Writer.WL($@" AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, {baseUnitVariableName}.As({_unitEnumName}.{unit.SingularName}), {unit.PluralName}Tolerance);"); - } - Writer.WL($@" }} @@ -156,13 +123,12 @@ public void ToUnit() { var asQuantityVariableName = $"{unit.SingularName.ToLowerInvariant()}Quantity"; - Writer.WL(); + Writer.WL(""); Writer.WL($@" var {asQuantityVariableName} = {baseUnitVariableName}.ToUnit({_unitEnumName}.{unit.SingularName}); AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, (double){asQuantityVariableName}.Value, {unit.PluralName}Tolerance); Assert.Equal({_unitEnumName}.{unit.SingularName}, {asQuantityVariableName}.Unit);"); } - Writer.WL($@" }} @@ -170,14 +136,10 @@ public void ToUnit() public void ConversionRoundTrip() {{ {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);"); - foreach (var unit in _quantity.Units) - { - Writer.WL($@" + foreach (var unit in _quantity.Units) Writer.WL($@" AssertEx.EqualTolerance(1, {_quantity.Name}.From{unit.PluralName}({baseUnitVariableName}.{unit.PluralName}).{_baseUnit.PluralName}, {unit.PluralName}Tolerance);"); - } - - Writer.WL(@" - } + Writer.WL($@" + }} "); if (_quantity.Logarithmic) { @@ -220,7 +182,7 @@ public void ArithmeticOperators() } else { - Writer.WL(); + Writer.WL(""); } Writer.WL($@" diff --git a/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs index 5dbff53de5..3580502e0b 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTestStubGenerator.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using CodeGen.JsonTypes; namespace CodeGen.Generators.UnitsNetGen diff --git a/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs index 55226e6e65..eaf6220511 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTypeGenerator.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using CodeGen.Helpers; using CodeGen.JsonTypes; @@ -53,11 +50,11 @@ public enum {_unitEnumName} {unit.SingularName},"); } - Writer.WL(@" - } + Writer.WL($@" + }} #pragma warning restore 1591 -}"); +}}"); return Writer.ToString(); } } diff --git a/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs index 4d9b012d2e..fc3507efa9 100644 --- a/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetWrcGen/QuantityGenerator.cs @@ -10,12 +10,12 @@ namespace CodeGen.Generators.UnitsNetWrcGen { internal class QuantityGenerator : GeneratorBase { - private readonly Unit _baseUnit; + private readonly Quantity _quantity; private readonly bool _isDimensionless; - private readonly Quantity _quantity; private readonly string _unitEnumName; private readonly string _valueType; + private readonly Unit _baseUnit; public QuantityGenerator(Quantity quantity) { @@ -28,15 +28,16 @@ public QuantityGenerator(Quantity quantity) _valueType = quantity.BaseType; _unitEnumName = $"{quantity.Name}Unit"; - var baseDimensions = quantity.BaseDimensions; + BaseDimensions baseDimensions = quantity.BaseDimensions; _isDimensionless = baseDimensions == null || - baseDimensions.L == 0 && - baseDimensions.M == 0 && - baseDimensions.T == 0 && - baseDimensions.I == 0 && - baseDimensions.Θ == 0 && - baseDimensions.N == 0 && - baseDimensions.J == 0; + baseDimensions.L == 0 && + baseDimensions.M == 0 && + baseDimensions.T == 0 && + baseDimensions.I == 0 && + baseDimensions.Θ == 0 && + baseDimensions.N == 0 && + baseDimensions.J == 0; + } public override string Generate() @@ -93,13 +94,13 @@ public sealed partial class {_quantity.Name} : IQuantity GenerateConversionMethods(); GenerateToString(); - Writer.WL(@" + Writer.WL($@" private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) - { + {{ return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; - } - } -}"); + }} + }} +}}"); return Writer.ToString(); } @@ -154,9 +155,9 @@ private void GenerateInstanceConstructors() _value = Guard.EnsureValidNumber(value, nameof(value));" : @" _value = value;"); - Writer.WL(@" + Writer.WL($@" _unit = unit; - } + }} "); } @@ -211,7 +212,7 @@ private void GenerateStaticProperties() private void GenerateProperties() { - Writer.WL(@" + Writer.WL($@" #region Properties /// @@ -671,7 +672,7 @@ public double As({_unitEnumName} unit) private void GenerateToString() { - Writer.WL(@" + Writer.WL($@" #region ToString Methods /// @@ -679,9 +680,9 @@ private void GenerateToString() /// /// String representation. public override string ToString() - { + {{ return ToString(null); - } + }} /// /// Get string representation of value and unit. Using two significant digits after radix. @@ -689,10 +690,10 @@ public override string ToString() /// String representation. /// Name of culture (ex: ""en-US"") to use for localization and number formatting. Defaults to if null. public string ToString([CanBeNull] string cultureName) - { + {{ var provider = cultureName; return ToString(provider, 2); - } + }} /// /// Get string representation of value and unit. @@ -701,22 +702,22 @@ public string ToString([CanBeNull] string cultureName) /// String representation. /// Name of culture (ex: ""en-US"") to use for localization and number formatting. Defaults to if null. public string ToString(string cultureName, int significantDigitsAfterRadix) - { + {{ var provider = cultureName; var value = Convert.ToDouble(Value); var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); return ToString(provider, format); - } + }} /// /// Get string representation of value and unit. /// - /// String format to use. Default: ""{0:0.##} {1} for value and unit abbreviation respectively."" + /// String format to use. Default: ""{{0:0.##}} {{1}} for value and unit abbreviation respectively."" /// Arguments for string format. Value and unit are implicitly included as arguments 0 and 1. /// String representation. /// Name of culture (ex: ""en-US"") to use for localization and number formatting. Defaults to if null. public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) - { + {{ var provider = GetFormatProviderFromCultureName(cultureName); if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); @@ -726,21 +727,21 @@ public string ToString([CanBeNull] string cultureName, [NotNull] string format, var value = Convert.ToDouble(Value); var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); - } + }} #endregion "); } - /// + /// internal static string GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText); - /// + /// internal static string GetObsoleteAttributeOrNull(Unit unit) => GetObsoleteAttributeOrNull(unit.ObsoleteText); /// - /// Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string - /// It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats + /// Returns the Obsolete attribute if ObsoleteText has been defined on the JSON input - otherwise returns empty string + /// It is up to the consumer to wrap any padding/new lines in order to keep to correct indentation formats /// private static string GetObsoleteAttributeOrNull(string obsoleteText) => string.IsNullOrWhiteSpace(obsoleteText) ? null diff --git a/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs index 8b7d07bbca..582b299d6a 100644 --- a/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs +++ b/CodeGen/Generators/UnitsNetWrcGen/QuantityTypeGenerator.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using CodeGen.JsonTypes; namespace CodeGen.Generators.UnitsNetWrcGen @@ -31,11 +28,8 @@ public enum QuantityType { Undefined = 0,"); foreach (var quantity in _quantities) - { Writer.WL($@" {quantity.Name},"); - } - Writer.WL(@" } }"); diff --git a/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs index b8466156f1..133a34850b 100644 --- a/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetWrcGen/StaticQuantityGenerator.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using CodeGen.Helpers; using CodeGen.JsonTypes; @@ -54,14 +51,14 @@ internal static bool TryFrom(double value, Enum unit, out IQuantity quantity) return true;"); } - Writer.WL(@" + Writer.WL($@" default: - { + {{ quantity = default(IQuantity); return false; - } - } - } + }} + }} + }} /// internal static IQuantity Parse(Type quantityType, string quantityString) => Parse(null, quantityType, quantityString); @@ -75,14 +72,14 @@ internal static bool TryFrom(double value, Enum unit, out IQuantity quantity) /// The parsed quantity. /// Type must be of type UnitsNet.IQuantity -or- Type is not a known quantity type. internal static IQuantity Parse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString) - { + {{ if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) - throw new ArgumentException($""Type {quantityType} must be of type UnitsNet.IQuantity.""); + throw new ArgumentException($""Type {{quantityType}} must be of type UnitsNet.IQuantity.""); if (TryParse(formatProvider, quantityType, quantityString, out IQuantity quantity)) return quantity; - throw new ArgumentException($""Quantity string could not be parsed to quantity {quantityType}.""); - } + throw new ArgumentException($""Quantity string could not be parsed to quantity {{quantityType}}.""); + }} /// internal static bool TryParse(Type quantityType, string quantityString, out IQuantity quantity) => @@ -97,7 +94,7 @@ internal static bool TryParse(Type quantityType, string quantityString, out IQua /// The resulting quantity if successful, otherwise default. /// The parsed quantity. internal static bool TryParse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString, out IQuantity quantity) - { + {{ quantity = default(IQuantity); if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) @@ -113,12 +110,12 @@ internal static bool TryParse([CanBeNull] IFormatProvider formatProvider, Type q "); } - Writer.WL(@" + Writer.WL($@" throw new ArgumentException( - $""Type {quantityType} is not a known quantity type. Did you pass in a third-party quantity type defined outside UnitsNet library?""); - } - } -}"); + $""Type {{quantityType}} is not a known quantity type. Did you pass in a third-party quantity type defined outside UnitsNet library?""); + }} + }} +}}"); return Writer.ToString(); } } diff --git a/CodeGen/Generators/UnitsNetWrcGen/UnitAbbreviationsCacheGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/UnitAbbreviationsCacheGenerator.cs index 3721be1359..5695ad777a 100644 --- a/CodeGen/Generators/UnitsNetWrcGen/UnitAbbreviationsCacheGenerator.cs +++ b/CodeGen/Generators/UnitsNetWrcGen/UnitAbbreviationsCacheGenerator.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using System.Linq; using CodeGen.JsonTypes; diff --git a/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs b/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs index e95c822c0e..939d947a17 100644 --- a/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs +++ b/CodeGen/Generators/UnitsNetWrcGen/UnitTypeGenerator.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using CodeGen.Helpers; using CodeGen.JsonTypes; @@ -53,11 +50,11 @@ public enum {_unitEnumName} {unit.SingularName},"); } - Writer.WL(@" - } + Writer.WL($@" + }} #pragma warning restore 1591 -}"); +}}"); return Writer.ToString(); } } diff --git a/CodeGen/Helpers/MyTextWriter.cs b/CodeGen/Helpers/MyTextWriter.cs index b89940c3be..3fae829a09 100644 --- a/CodeGen/Helpers/MyTextWriter.cs +++ b/CodeGen/Helpers/MyTextWriter.cs @@ -36,8 +36,7 @@ private string GetIndent(int indentLevel) } /// - /// Write line with current indent. Trims preceding newline if any, to simplify code formatting when calling this - /// method. + /// Write line with current indent. Trims preceding newline if any, to simplify code formatting when calling this method. /// /// The indent level to prepend the text with. /// The text to write @@ -48,8 +47,7 @@ public void WL(int indentLevel, string text = "") } /// - /// Write line with current indent. Trims preceding newline if any, to simplify code formatting when calling this - /// method. + /// Write line with current indent. Trims preceding newline if any, to simplify code formatting when calling this method. /// /// The text to write public void WL(string text = "") @@ -59,8 +57,7 @@ public void WL(string text = "") } /// - /// Write with current indent, but no newline. Trims preceding newline if any, to simplify code formatting when calling - /// this method. + /// Write with current indent, but no newline. Trims preceding newline if any, to simplify code formatting when calling this method. /// /// The text to write public void W(string text = "") @@ -88,7 +85,7 @@ public override string ToString() } /// - /// Write line with current ident only if actually contains text and not just whitespace. + /// Write line with current ident only if actually contains text and not just whitespace. /// /// The level of indentation to prepend to the text. /// The text to write. @@ -99,16 +96,14 @@ public void WLIfText(int indentLevel, string text) } /// - /// Write line with current ident only if is true. + /// Write line with current ident only if is true. /// /// The condition. /// The text to write. public void WLCondition(bool condition, string text) { if (condition) - { WL(text); - } } } } diff --git a/CodeGen/Helpers/StringExtensions.cs b/CodeGen/Helpers/StringExtensions.cs index 70c0cbaef4..9091491889 100644 --- a/CodeGen/Helpers/StringExtensions.cs +++ b/CodeGen/Helpers/StringExtensions.cs @@ -6,12 +6,12 @@ namespace CodeGen.Helpers internal static class StringExtensions { /// - /// Returns true if string is not null and not whitespace. + /// Returns true if string is not null and not whitespace. /// public static bool HasText(this string str) => !string.IsNullOrWhiteSpace(str); /// - /// Example: "Kilo" + ToCamelCase("NewtonPerMeter") => "KilonewtonPerMeter" + /// Example: "Kilo" + ToCamelCase("NewtonPerMeter") => "KilonewtonPerMeter" /// public static string ToCamelCase(this string str) { diff --git a/CodeGen/JsonTypes/BaseDimensions.cs b/CodeGen/JsonTypes/BaseDimensions.cs index 87cada0970..a6caad21fd 100644 --- a/CodeGen/JsonTypes/BaseDimensions.cs +++ b/CodeGen/JsonTypes/BaseDimensions.cs @@ -10,22 +10,16 @@ internal class BaseDimensions /// AmountOfSubstance. public int N = 0; - /// ElectricCurrent. public int I = 0; - /// Length. public int L = 0; - /// LuminousIntensity. public int J = 0; - /// Mass. public int M = 0; - /// Temperature. public int Θ = 0; - /// Time. public int T = 0; diff --git a/CodeGen/JsonTypes/BaseUnits.cs b/CodeGen/JsonTypes/BaseUnits.cs index e62aedc5b0..46f0887811 100644 --- a/CodeGen/JsonTypes/BaseUnits.cs +++ b/CodeGen/JsonTypes/BaseUnits.cs @@ -10,22 +10,16 @@ internal class BaseUnits /// AmountOfSubstance. public string N; - /// ElectricCurrent. public string I; - /// Length. public string L; - /// LuminousIntensity. public string J; - /// Mass. public string M; - /// Temperature. public string Θ; - /// Time. public string T; diff --git a/CodeGen/JsonTypes/Prefix.cs b/CodeGen/JsonTypes/Prefix.cs index a4ae586cce..62d106bb39 100644 --- a/CodeGen/JsonTypes/Prefix.cs +++ b/CodeGen/JsonTypes/Prefix.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - namespace CodeGen.JsonTypes { internal enum Prefix @@ -35,4 +32,4 @@ internal enum Prefix Pebi, Exbi } -} +} \ No newline at end of file diff --git a/CodeGen/JsonTypes/Quantity.cs b/CodeGen/JsonTypes/Quantity.cs index 4f2a91158a..0888bf8464 100644 --- a/CodeGen/JsonTypes/Quantity.cs +++ b/CodeGen/JsonTypes/Quantity.cs @@ -2,6 +2,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; namespace CodeGen.JsonTypes { diff --git a/CodeGen/PrefixInfo.cs b/CodeGen/PrefixInfo.cs index ab6c4ba796..73d62c9517 100644 --- a/CodeGen/PrefixInfo.cs +++ b/CodeGen/PrefixInfo.cs @@ -1,6 +1,3 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using System; using System.Collections.Generic; using System.Linq; @@ -21,20 +18,32 @@ internal class PrefixInfo // when creating decimal conversion functions in CodeGen.Generator.FixConversionFunctionsForDecimalValueTypes. // SI prefixes - new PrefixInfo(Prefix.Yocto, "1e-24d", "y"), new PrefixInfo(Prefix.Zepto, "1e-21d", "z"), - new PrefixInfo(Prefix.Atto, "1e-18d", "a", (Russian, "а")), new PrefixInfo(Prefix.Femto, "1e-15d", "f", (Russian, "ф")), - new PrefixInfo(Prefix.Pico, "1e-12d", "p", (Russian, "п")), new PrefixInfo(Prefix.Nano, "1e-9d", "n", (Russian, "н")), - new PrefixInfo(Prefix.Micro, "1e-6d", "µ", (Russian, "мк")), new PrefixInfo(Prefix.Milli, "1e-3d", "m", (Russian, "м")), - new PrefixInfo(Prefix.Centi, "1e-2d", "c", (Russian, "с")), new PrefixInfo(Prefix.Deci, "1e-1d", "d", (Russian, "д")), - new PrefixInfo(Prefix.Deca, "1e1d", "da", (Russian, "да")), new PrefixInfo(Prefix.Hecto, "1e2d", "h", (Russian, "г")), - new PrefixInfo(Prefix.Kilo, "1e3d", "k", (Russian, "к")), new PrefixInfo(Prefix.Mega, "1e6d", "M", (Russian, "М")), - new PrefixInfo(Prefix.Giga, "1e9d", "G", (Russian, "Г")), new PrefixInfo(Prefix.Tera, "1e12d", "T", (Russian, "Т")), - new PrefixInfo(Prefix.Peta, "1e15d", "P", (Russian, "П")), new PrefixInfo(Prefix.Exa, "1e18d", "E", (Russian, "Э")), - new PrefixInfo(Prefix.Zetta, "1e21d", "Z"), new PrefixInfo(Prefix.Yotta, "1e24d", "Y"), + new PrefixInfo(Prefix.Yocto, "1e-24d", "y"), + new PrefixInfo(Prefix.Zepto, "1e-21d", "z"), + new PrefixInfo(Prefix.Atto, "1e-18d", "a", (Russian, "а")), + new PrefixInfo(Prefix.Femto, "1e-15d", "f", (Russian, "ф")), + new PrefixInfo(Prefix.Pico, "1e-12d", "p", (Russian, "п")), + new PrefixInfo(Prefix.Nano, "1e-9d", "n", (Russian, "н")), + new PrefixInfo(Prefix.Micro, "1e-6d", "µ", (Russian, "мк")), + new PrefixInfo(Prefix.Milli, "1e-3d", "m", (Russian, "м")), + new PrefixInfo(Prefix.Centi, "1e-2d", "c", (Russian, "с")), + new PrefixInfo(Prefix.Deci, "1e-1d", "d", (Russian, "д")), + new PrefixInfo(Prefix.Deca, "1e1d", "da", (Russian, "да")), + new PrefixInfo(Prefix.Hecto, "1e2d", "h", (Russian, "г")), + new PrefixInfo(Prefix.Kilo, "1e3d", "k", (Russian, "к")), + new PrefixInfo(Prefix.Mega, "1e6d", "M", (Russian, "М")), + new PrefixInfo(Prefix.Giga, "1e9d", "G", (Russian, "Г")), + new PrefixInfo(Prefix.Tera, "1e12d", "T", (Russian, "Т")), + new PrefixInfo(Prefix.Peta, "1e15d", "P", (Russian, "П")), + new PrefixInfo(Prefix.Exa, "1e18d", "E", (Russian, "Э")), + new PrefixInfo(Prefix.Zetta, "1e21d", "Z"), + new PrefixInfo(Prefix.Yotta, "1e24d", "Y"), // Binary prefixes - new PrefixInfo(Prefix.Kibi, "1024d", "Ki"), new PrefixInfo(Prefix.Mebi, "(1024d * 1024)", "Mi"), - new PrefixInfo(Prefix.Gibi, "(1024d * 1024 * 1024)", "Gi"), new PrefixInfo(Prefix.Tebi, "(1024d * 1024 * 1024 * 1024)", "Ti"), + new PrefixInfo(Prefix.Kibi, "1024d", "Ki"), + new PrefixInfo(Prefix.Mebi, "(1024d * 1024)", "Mi"), + new PrefixInfo(Prefix.Gibi, "(1024d * 1024 * 1024)", "Gi"), + new PrefixInfo(Prefix.Tebi, "(1024d * 1024 * 1024 * 1024)", "Ti"), new PrefixInfo(Prefix.Pebi, "(1024d * 1024 * 1024 * 1024 * 1024)", "Pi"), new PrefixInfo(Prefix.Exbi, "(1024d * 1024 * 1024 * 1024 * 1024 * 1024)", "Ei") }.ToDictionary(prefixInfo => prefixInfo.Prefix); diff --git a/CodeGen/Program.cs b/CodeGen/Program.cs index e26fe9655a..c930b4bd1d 100644 --- a/CodeGen/Program.cs +++ b/CodeGen/Program.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; using System.Diagnostics; using System.IO; using System.Linq; @@ -68,9 +65,7 @@ private static int Main(bool verbose = false, DirectoryInfo repositoryRoot = nul UnitsNetGenerator.Generate(rootDir, quantities); if (!skipWrc) - { UnitsNetWrcGenerator.Generate(rootDir, quantities); - } Log.Information($"Completed in {sw.ElapsedMilliseconds} ms!", ConsoleColor.Green); return 0; diff --git a/Common/UnitDefinitions/Acceleration.json b/Common/UnitDefinitions/Acceleration.json index 3eb336c3e4..ed292ace3c 100644 --- a/Common/UnitDefinitions/Acceleration.json +++ b/Common/UnitDefinitions/Acceleration.json @@ -1,8 +1,7 @@ { "Name": "Acceleration", "BaseUnit": "MeterPerSecondSquared", - "XmlDoc": - "Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration.", + "XmlDoc": "Acceleration, in physics, is the rate at which the velocity of an object changes over time. An object's acceleration is the net result of any and all forces acting on the object, as described by Newton's Second Law. The SI unit for acceleration is the Meter per second squared (m/s²). Accelerations are vector quantities (they have magnitude and direction) and add according to the parallelogram law. As a vector, the calculated net force is equal to the product of the object's mass (a scalar quantity) and the acceleration.", "BaseDimensions": { "L": 1, "T": -2 @@ -17,11 +16,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m/s²"] + "Abbreviations": [ "m/s²" ] } ] }, @@ -37,7 +36,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["in/s²"] + "Abbreviations": [ "in/s²" ] } ] }, @@ -53,7 +52,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft/s²"] + "Abbreviations": [ "ft/s²" ] } ] }, @@ -69,7 +68,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kn/s"] + "Abbreviations": [ "kn/s" ] } ] }, @@ -85,7 +84,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kn/min"] + "Abbreviations": [ "kn/min" ] } ] }, @@ -101,7 +100,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kn/h"] + "Abbreviations": [ "kn/h" ] } ] }, @@ -117,7 +116,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g"] + "Abbreviations": [ "g" ] } ] } diff --git a/Common/UnitDefinitions/AmountOfSubstance.json b/Common/UnitDefinitions/AmountOfSubstance.json index 3992bfea02..101b13dcde 100644 --- a/Common/UnitDefinitions/AmountOfSubstance.json +++ b/Common/UnitDefinitions/AmountOfSubstance.json @@ -1,8 +1,7 @@ { "Name": "AmountOfSubstance", "BaseUnit": "Mole", - "XmlDoc": - "Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals.", + "XmlDoc": "Mole is the amount of substance containing Avagadro's Number (6.02 x 10 ^ 23) of real particles such as molecules,atoms, ions or radicals.", "BaseDimensions": { "N": 1 }, @@ -15,11 +14,11 @@ "BaseUnits": { "N": "Mole" }, - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega"], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mol"] + "Abbreviations": [ "mol" ] } ] }, @@ -31,11 +30,11 @@ }, "FromUnitToBaseFunc": "x*453.59237", "FromBaseToUnitFunc": "x/453.59237", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbmol"] + "Abbreviations": [ "lbmol" ] } ] } diff --git a/Common/UnitDefinitions/AmplitudeRatio.json b/Common/UnitDefinitions/AmplitudeRatio.json index 0a71dae003..b735680ad4 100644 --- a/Common/UnitDefinitions/AmplitudeRatio.json +++ b/Common/UnitDefinitions/AmplitudeRatio.json @@ -13,7 +13,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dBV"] + "Abbreviations": [ "dBV" ] } ] }, @@ -25,7 +25,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dBµV"] + "Abbreviations": [ "dBµV" ] } ] }, @@ -37,7 +37,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dBmV"] + "Abbreviations": [ "dBmV" ] } ] }, @@ -49,7 +49,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dBu"] + "Abbreviations": [ "dBu" ] } ] } diff --git a/Common/UnitDefinitions/Angle.json b/Common/UnitDefinitions/Angle.json index 953df60aba..e551955751 100644 --- a/Common/UnitDefinitions/Angle.json +++ b/Common/UnitDefinitions/Angle.json @@ -1,40 +1,39 @@ { "Name": "Angle", "BaseUnit": "Degree", - "XmlDoc": - "In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle.", + "XmlDoc": "In geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle.", "Units": [ { "SingularName": "Radian", "PluralName": "Radians", "FromUnitToBaseFunc": "x*180/Math.PI", "FromBaseToUnitFunc": "x/180*Math.PI", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["rad"] + "Abbreviations": [ "rad" ] }, { "Culture": "ru-RU", - "Abbreviations": ["рад"] + "Abbreviations": [ "рад" ] } ] }, { "SingularName": "Degree", "PluralName": "Degrees", - "Prefixes": ["Nano", "Micro", "Milli"], + "Prefixes": [ "Nano", "Micro", "Milli" ], "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°", "deg"] + "Abbreviations": [ "°", "deg" ] }, { "Culture": "ru-RU", - "Abbreviations": ["°"] + "Abbreviations": [ "°" ] } ] }, @@ -46,7 +45,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["'", "arcmin", "amin", "min"] + "Abbreviations": [ "'", "arcmin", "amin", "min" ] } ] }, @@ -58,7 +57,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["″", "arcsec", "asec", "sec"] + "Abbreviations": [ "″", "arcsec", "asec", "sec" ] } ] }, @@ -70,11 +69,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g"] + "Abbreviations": [ "g" ] }, { "Culture": "ru-RU", - "Abbreviations": ["g"] + "Abbreviations": [ "g" ] } ] }, @@ -86,11 +85,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["r"] + "Abbreviations": [ "r" ] }, { "Culture": "ru-RU", - "Abbreviations": ["r"] + "Abbreviations": [ "r" ] } ] } diff --git a/Common/UnitDefinitions/ApparentEnergy.json b/Common/UnitDefinitions/ApparentEnergy.json index ccd57d1e54..9f59768dd2 100644 --- a/Common/UnitDefinitions/ApparentEnergy.json +++ b/Common/UnitDefinitions/ApparentEnergy.json @@ -1,8 +1,7 @@ { "Name": "ApparentEnergy", "BaseUnit": "VoltampereHour", - "XmlDoc": - "A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules.", + "XmlDoc": "A unit for expressing the integral of apparent power over time, equal to the product of 1 volt-ampere and 1 hour, or to 3600 joules.", "BaseDimensions": { "L": 2, "M": 1, @@ -14,11 +13,11 @@ "PluralName": "VoltampereHours", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["VAh"] + "Abbreviations": [ "VAh" ] } ] } diff --git a/Common/UnitDefinitions/ApparentPower.json b/Common/UnitDefinitions/ApparentPower.json index f46f980550..83312e8d8e 100644 --- a/Common/UnitDefinitions/ApparentPower.json +++ b/Common/UnitDefinitions/ApparentPower.json @@ -1,8 +1,7 @@ { "Name": "ApparentPower", "BaseUnit": "Voltampere", - "XmlDoc": - "Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current.", + "XmlDoc": "Power engineers measure apparent power as the magnitude of the vector sum of active and reactive power. Apparent power is the product of the root-mean-square of voltage and current.", "BaseDimensions": { "L": 2, "M": 1, @@ -14,11 +13,11 @@ "PluralName": "Voltamperes", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega", "Giga"], + "Prefixes": [ "Kilo", "Mega", "Giga" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["VA"] + "Abbreviations": [ "VA" ] } ] } diff --git a/Common/UnitDefinitions/Area.json b/Common/UnitDefinitions/Area.json index b4cb808250..07d52dfd56 100644 --- a/Common/UnitDefinitions/Area.json +++ b/Common/UnitDefinitions/Area.json @@ -1,8 +1,7 @@ { "Name": "Area", "BaseUnit": "SquareMeter", - "XmlDoc": - "Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept).", + "XmlDoc": "Area is a quantity that expresses the extent of a two-dimensional surface or shape, or planar lamina, in the plane. Area can be understood as the amount of material with a given thickness that would be necessary to fashion a model of the shape, or the amount of paint necessary to cover the surface with a single coat.[1] It is the two-dimensional analog of the length of a curve (a one-dimensional concept) or the volume of a solid (a three-dimensional concept).", "BaseDimensions": { "L": 2 }, @@ -18,11 +17,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["km²"] + "Abbreviations": [ "km²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["км²"] + "Abbreviations": [ "км²" ] } ] }, @@ -37,11 +36,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m²"] + "Abbreviations": [ "m²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["м²"] + "Abbreviations": [ "м²" ] } ] }, @@ -56,11 +55,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dm²"] + "Abbreviations": [ "dm²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["дм²"] + "Abbreviations": [ "дм²" ] } ] }, @@ -75,11 +74,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cm²"] + "Abbreviations": [ "cm²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["см²"] + "Abbreviations": [ "см²" ] } ] }, @@ -94,11 +93,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mm²"] + "Abbreviations": [ "mm²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["мм²"] + "Abbreviations": [ "мм²" ] } ] }, @@ -113,11 +112,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["µm²"] + "Abbreviations": [ "µm²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["мкм²"] + "Abbreviations": [ "мкм²" ] } ] }, @@ -132,11 +131,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mi²"] + "Abbreviations": [ "mi²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["миля²"] + "Abbreviations": [ "миля²" ] } ] }, @@ -151,11 +150,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["yd²"] + "Abbreviations": [ "yd²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["ярд²"] + "Abbreviations": [ "ярд²" ] } ] }, @@ -170,11 +169,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft²"] + "Abbreviations": [ "ft²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["фут²"] + "Abbreviations": [ "фут²" ] } ] }, @@ -189,7 +188,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft² (US)"] + "Abbreviations": [ "ft² (US)" ] } ] }, @@ -204,11 +203,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["in²"] + "Abbreviations": [ "in²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["дюйм²"] + "Abbreviations": [ "дюйм²" ] } ] }, @@ -220,7 +219,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ac"] + "Abbreviations": [ "ac" ] } ] }, @@ -232,7 +231,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ha"] + "Abbreviations": [ "ha" ] } ] }, @@ -249,4 +248,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/AreaDensity.json b/Common/UnitDefinitions/AreaDensity.json index bf051fcb26..2b3623d107 100644 --- a/Common/UnitDefinitions/AreaDensity.json +++ b/Common/UnitDefinitions/AreaDensity.json @@ -19,7 +19,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kg/m²"] + "Abbreviations": [ "kg/m²" ] } ] } diff --git a/Common/UnitDefinitions/AreaMomentOfInertia.json b/Common/UnitDefinitions/AreaMomentOfInertia.json index 5fbe4e265c..0e288f8994 100644 --- a/Common/UnitDefinitions/AreaMomentOfInertia.json +++ b/Common/UnitDefinitions/AreaMomentOfInertia.json @@ -17,7 +17,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m⁴", "m^4"] + "Abbreviations": [ "m⁴", "m^4" ] } ] }, @@ -32,7 +32,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dm⁴", "dm^4"] + "Abbreviations": [ "dm⁴", "dm^4" ] } ] }, @@ -47,7 +47,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cm⁴", "cm^4"] + "Abbreviations": [ "cm⁴", "cm^4" ] } ] }, @@ -62,7 +62,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mm⁴", "mm^4"] + "Abbreviations": [ "mm⁴", "mm^4" ] } ] }, @@ -77,7 +77,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft⁴", "ft^4"] + "Abbreviations": [ "ft⁴", "ft^4" ] } ] }, @@ -92,7 +92,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["in⁴", "in^4"] + "Abbreviations": [ "in⁴", "in^4" ] } ] } diff --git a/Common/UnitDefinitions/BitRate.json b/Common/UnitDefinitions/BitRate.json index 1385d33d8b..b768a1c9e5 100644 --- a/Common/UnitDefinitions/BitRate.json +++ b/Common/UnitDefinitions/BitRate.json @@ -2,8 +2,7 @@ "Name": "BitRate", "BaseUnit": "BitPerSecond", "BaseType": "decimal", - "XmlDoc": - "In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time.", + "XmlDoc": "In telecommunications and computing, bit rate is the number of bits that are conveyed or processed per unit of time.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Bit_rate", "Units": [ { @@ -11,11 +10,11 @@ "PluralName": "BitsPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi"], + "Prefixes": [ "Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bit/s", "bps"] + "Abbreviations": [ "bit/s", "bps" ] } ] }, @@ -24,11 +23,11 @@ "PluralName": "BytesPerSecond", "FromUnitToBaseFunc": "x*8m", "FromBaseToUnitFunc": "x/8m", - "Prefixes": ["Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi"], + "Prefixes": [ "Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["B/s"] + "Abbreviations": [ "B/s" ] } ] } diff --git a/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json b/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json index e6ac382c2f..34b30675d7 100644 --- a/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json +++ b/Common/UnitDefinitions/BrakeSpecificFuelConsumption.json @@ -1,8 +1,7 @@ { "Name": "BrakeSpecificFuelConsumption", "BaseUnit": "KilogramPerJoule", - "XmlDoc": - "Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output.", + "XmlDoc": "Brake specific fuel consumption (BSFC) is a measure of the fuel efficiency of any prime mover that burns fuel and produces rotational, or shaft, power. It is typically used for comparing the efficiency of internal combustion engines with a shaft output.", "BaseDimensions": { "L": -2, "T": 2 @@ -16,7 +15,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/kWh"] + "Abbreviations": [ "g/kWh" ] } ] }, @@ -28,7 +27,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kg/J"] + "Abbreviations": [ "kg/J" ] } ] }, @@ -41,7 +40,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/hph"] + "Abbreviations": [ "lb/hph" ] } ] } diff --git a/Common/UnitDefinitions/Capacitance.json b/Common/UnitDefinitions/Capacitance.json index 70005c3b8d..5d992e9230 100644 --- a/Common/UnitDefinitions/Capacitance.json +++ b/Common/UnitDefinitions/Capacitance.json @@ -21,11 +21,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Kilo", "Mega"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["F"] + "Abbreviations": [ "F" ] } ] } diff --git a/Common/UnitDefinitions/CoefficientOfThermalExpansion.json b/Common/UnitDefinitions/CoefficientOfThermalExpansion.json index cc4ec14723..793d9363ae 100644 --- a/Common/UnitDefinitions/CoefficientOfThermalExpansion.json +++ b/Common/UnitDefinitions/CoefficientOfThermalExpansion.json @@ -17,7 +17,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["K⁻¹", "1/K"] + "Abbreviations": [ "K⁻¹", "1/K" ] } ] }, @@ -32,7 +32,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°C⁻¹", "1/°C"] + "Abbreviations": [ "°C⁻¹", "1/°C" ] } ] }, @@ -47,7 +47,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°F⁻¹", "1/°F"] + "Abbreviations": [ "°F⁻¹", "1/°F" ] } ] } diff --git a/Common/UnitDefinitions/Density.json b/Common/UnitDefinitions/Density.json index b99292169c..0849bec96a 100644 --- a/Common/UnitDefinitions/Density.json +++ b/Common/UnitDefinitions/Density.json @@ -17,11 +17,11 @@ }, "FromUnitToBaseFunc": "x/1e-6", "FromBaseToUnitFunc": "x*1e-6", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/mm³"] + "Abbreviations": [ "g/mm³" ] } ] }, @@ -34,11 +34,11 @@ }, "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/cm³"] + "Abbreviations": [ "g/cm³" ] } ] }, @@ -51,15 +51,15 @@ }, "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": ["Kilo", "Milli", "Micro"], + "Prefixes": [ "Kilo", "Milli", "Micro" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/m³"] + "Abbreviations": [ "g/m³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["г/м³"] + "Abbreviations": [ "г/м³" ] } ] }, @@ -72,11 +72,11 @@ }, "FromUnitToBaseFunc": "x/3.6127298147753e-5", "FromBaseToUnitFunc": "x*3.6127298147753e-5", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/in³"], + "Abbreviations": [ "lb/in³" ], "AbbreviationsForPrefixes": { "Kilo": "kip/in³" } } ] @@ -90,11 +90,11 @@ }, "FromUnitToBaseFunc": "x/0.062427961", "FromBaseToUnitFunc": "x*0.062427961", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/ft³"], + "Abbreviations": [ "lb/ft³" ], "AbbreviationsForPrefixes": { "Kilo": "kip/ft³" } } ] @@ -111,7 +111,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t/mm³"] + "Abbreviations": [ "t/mm³" ] } ] }, @@ -127,7 +127,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t/cm³"] + "Abbreviations": [ "t/cm³" ] } ] }, @@ -143,7 +143,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t/m³"] + "Abbreviations": [ "t/m³" ] } ] }, @@ -159,7 +159,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["slug/ft³"] + "Abbreviations": [ "slug/ft³" ] } ] }, @@ -168,11 +168,11 @@ "PluralName": "GramsPerLiter", "FromUnitToBaseFunc": "x/1", "FromBaseToUnitFunc": "x*1", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/L"] + "Abbreviations": [ "g/L" ] } ] }, @@ -181,11 +181,11 @@ "PluralName": "GramsPerDeciLiter", "FromUnitToBaseFunc": "x/1e-1", "FromBaseToUnitFunc": "x*1e-1", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/dl"] + "Abbreviations": [ "g/dl" ] } ] }, @@ -194,11 +194,11 @@ "PluralName": "GramsPerMilliliter", "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/ml"] + "Abbreviations": [ "g/ml" ] } ] }, @@ -210,7 +210,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppg (U.S.)"] + "Abbreviations": [ "ppg (U.S.)" ] } ] }, @@ -222,7 +222,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppg (imp.)"] + "Abbreviations": [ "ppg (imp.)" ] } ] }, @@ -238,9 +238,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kg/l"] + "Abbreviations": [ "kg/l" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/Duration.json b/Common/UnitDefinitions/Duration.json index f821ccae98..9edffaeae3 100644 --- a/Common/UnitDefinitions/Duration.json +++ b/Common/UnitDefinitions/Duration.json @@ -1,8 +1,7 @@ { "Name": "Duration", "BaseUnit": "Second", - "XmlDoc": - "Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them.", + "XmlDoc": "Time is a dimension in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them.", "BaseDimensions": { "T": 1 }, @@ -18,11 +17,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["yr", "year", "years"] + "Abbreviations": [ "yr", "year", "years" ] }, { "Culture": "ru-RU", - "Abbreviations": ["год"] + "Abbreviations": [ "год" ] } ] }, @@ -37,11 +36,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mo", "month", "months"] + "Abbreviations": [ "mo", "month", "months" ] }, { "Culture": "ru-RU", - "Abbreviations": ["месяц"] + "Abbreviations": [ "месяц" ] } ] }, @@ -56,11 +55,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["wk", "week", "weeks"] + "Abbreviations": [ "wk", "week", "weeks" ] }, { "Culture": "ru-RU", - "Abbreviations": ["мин"] + "Abbreviations": [ "мин" ] } ] }, @@ -75,11 +74,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["d", "day", "days"] + "Abbreviations": [ "d", "day", "days" ] }, { "Culture": "ru-RU", - "Abbreviations": ["д"] + "Abbreviations": [ "д" ] } ] }, @@ -94,11 +93,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["h", "hr", "hrs", "hour", "hours"] + "Abbreviations": [ "h", "hr", "hrs", "hour", "hours" ] }, { "Culture": "ru-RU", - "Abbreviations": ["ч"] + "Abbreviations": [ "ч" ] } ] }, @@ -113,11 +112,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m", "min", "minute", "minutes"] + "Abbreviations": [ "m", "min", "minute", "minutes" ] }, { "Culture": "ru-RU", - "Abbreviations": ["мин"] + "Abbreviations": [ "мин" ] } ] }, @@ -129,17 +128,17 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli"], + "Prefixes": [ "Nano", "Micro", "Milli" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["s", "sec", "secs", "second", "seconds"] + "Abbreviations": [ "s", "sec", "secs", "second", "seconds" ] }, { "Culture": "ru-RU", - "Abbreviations": ["с", "сек"] + "Abbreviations": [ "с", "сек" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/DynamicViscosity.json b/Common/UnitDefinitions/DynamicViscosity.json index 54103be9c0..8770ba982b 100644 --- a/Common/UnitDefinitions/DynamicViscosity.json +++ b/Common/UnitDefinitions/DynamicViscosity.json @@ -1,8 +1,7 @@ { "Name": "DynamicViscosity", "BaseUnit": "NewtonSecondPerMeterSquared", - "XmlDoc": - "The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds", + "XmlDoc": "The dynamic (shear) viscosity of a fluid expresses its resistance to shearing flows, where adjacent layers move parallel to each other with different speeds", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity", "BaseDimensions": { "L": -1, @@ -18,7 +17,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Ns/m²"] + "Abbreviations": [ "Ns/m²" ] } ] }, @@ -27,11 +26,11 @@ "PluralName": "PascalSeconds", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Milli", "Micro"], + "Prefixes": [ "Milli", "Micro" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Pa·s", "PaS"] + "Abbreviations": [ "Pa·s", "PaS" ] } ] }, @@ -40,11 +39,11 @@ "PluralName": "Poise", "FromUnitToBaseFunc": "x/10", "FromBaseToUnitFunc": "x*10", - "Prefixes": ["Centi"], + "Prefixes": [ "Centi" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["P"] + "Abbreviations": [ "P" ] } ] }, @@ -56,7 +55,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["reyn"] + "Abbreviations": [ "reyn" ] } ] }, @@ -68,7 +67,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf·s/in²"] + "Abbreviations": [ "lbf·s/in²" ] } ] }, @@ -80,7 +79,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf·s/ft²"] + "Abbreviations": [ "lbf·s/ft²" ] } ] } diff --git a/Common/UnitDefinitions/ElectricAdmittance.json b/Common/UnitDefinitions/ElectricAdmittance.json index 65799a269f..03b5b9b9a2 100644 --- a/Common/UnitDefinitions/ElectricAdmittance.json +++ b/Common/UnitDefinitions/ElectricAdmittance.json @@ -1,8 +1,7 @@ { "Name": "ElectricAdmittance", "BaseUnit": "Siemens", - "XmlDoc": - "Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S).", + "XmlDoc": "Electric admittance is a measure of how easily a circuit or device will allow a current to flow. It is defined as the inverse of impedance. The SI unit of admittance is the siemens (symbol S).", "BaseDimensions": { "L": -2, "M": -1, @@ -15,11 +14,11 @@ "PluralName": "Siemens", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli"], + "Prefixes": [ "Nano", "Micro", "Milli" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["S"] + "Abbreviations": [ "S" ] } ] } diff --git a/Common/UnitDefinitions/ElectricCharge.json b/Common/UnitDefinitions/ElectricCharge.json index 51c25f2abe..36e28fc9ff 100644 --- a/Common/UnitDefinitions/ElectricCharge.json +++ b/Common/UnitDefinitions/ElectricCharge.json @@ -1,8 +1,7 @@ { "Name": "ElectricCharge", "BaseUnit": "Coulomb", - "XmlDoc": - "Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field.", + "XmlDoc": "Electric charge is the physical property of matter that causes it to experience a force when placed in an electromagnetic field.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electric_charge", "BaseDimensions": { "T": 1, @@ -17,7 +16,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["C"] + "Abbreviations": [ "C" ] } ] }, @@ -26,11 +25,11 @@ "PluralName": "AmpereHours", "FromUnitToBaseFunc": "x/2.77777777777e-4", "FromBaseToUnitFunc": "x*2.77777777777e-4", - "Prefixes": ["Milli", "Kilo", "Mega"], + "Prefixes": [ "Milli", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["A-h", "Ah"] + "Abbreviations": [ "A-h", "Ah" ] } ] } diff --git a/Common/UnitDefinitions/ElectricChargeDensity.json b/Common/UnitDefinitions/ElectricChargeDensity.json index 264148a10c..3282494a74 100644 --- a/Common/UnitDefinitions/ElectricChargeDensity.json +++ b/Common/UnitDefinitions/ElectricChargeDensity.json @@ -22,7 +22,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["C/m³"] + "Abbreviations": [ "C/m³" ] } ] } diff --git a/Common/UnitDefinitions/ElectricConductance.json b/Common/UnitDefinitions/ElectricConductance.json index 96252c9197..52f48b373a 100644 --- a/Common/UnitDefinitions/ElectricConductance.json +++ b/Common/UnitDefinitions/ElectricConductance.json @@ -1,8 +1,7 @@ { "Name": "ElectricConductance", "BaseUnit": "Siemens", - "XmlDoc": - "The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor.", + "XmlDoc": "The electrical conductance of an electrical conductor is a measure of the easeness to pass an electric current through that conductor.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance", "BaseDimensions": { "L": -2, @@ -16,11 +15,11 @@ "PluralName": "Siemens", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Milli", "Micro"], + "Prefixes": [ "Milli", "Micro" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["S"] + "Abbreviations": [ "S" ] } ] } diff --git a/Common/UnitDefinitions/ElectricConductivity.json b/Common/UnitDefinitions/ElectricConductivity.json index 3133a95017..77d38bd48e 100644 --- a/Common/UnitDefinitions/ElectricConductivity.json +++ b/Common/UnitDefinitions/ElectricConductivity.json @@ -1,8 +1,7 @@ { "Name": "ElectricConductivity", "BaseUnit": "SiemensPerMeter", - "XmlDoc": - "Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current.", + "XmlDoc": "Electrical conductivity or specific conductance is the reciprocal of electrical resistivity, and measures a material's ability to conduct an electric current.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity", "BaseDimensions": { "L": -3, @@ -25,7 +24,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["S/m"] + "Abbreviations": [ "S/m" ] } ] }, @@ -37,7 +36,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["S/in"] + "Abbreviations": [ "S/in" ] } ] }, @@ -49,7 +48,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["S/ft"] + "Abbreviations": [ "S/ft" ] } ] } diff --git a/Common/UnitDefinitions/ElectricCurrent.json b/Common/UnitDefinitions/ElectricCurrent.json index 051a5fc6ae..d3e9305926 100644 --- a/Common/UnitDefinitions/ElectricCurrent.json +++ b/Common/UnitDefinitions/ElectricCurrent.json @@ -1,8 +1,7 @@ { "Name": "ElectricCurrent", "BaseUnit": "Ampere", - "XmlDoc": - "An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma.", + "XmlDoc": "An electric current is a flow of electric charge. In electric circuits this charge is often carried by moving electrons in a wire. It can also be carried by ions in an electrolyte, or by both ions and electrons such as in a plasma.", "BaseDimensions": { "I": 1 }, @@ -15,11 +14,11 @@ "BaseUnits": { "I": "Ampere" }, - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Kilo", "Mega"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["A"] + "Abbreviations": [ "A" ] } ] } diff --git a/Common/UnitDefinitions/ElectricCurrentDensity.json b/Common/UnitDefinitions/ElectricCurrentDensity.json index 6f4b7ff2d9..dbbb57ac0f 100644 --- a/Common/UnitDefinitions/ElectricCurrentDensity.json +++ b/Common/UnitDefinitions/ElectricCurrentDensity.json @@ -20,7 +20,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["A/m²"] + "Abbreviations": [ "A/m²" ] } ] }, @@ -36,7 +36,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["A/in²"] + "Abbreviations": [ "A/in²" ] } ] }, @@ -52,7 +52,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["A/ft²"] + "Abbreviations": [ "A/ft²" ] } ] } diff --git a/Common/UnitDefinitions/ElectricCurrentGradient.json b/Common/UnitDefinitions/ElectricCurrentGradient.json index cc4f87aeb2..188fffda98 100644 --- a/Common/UnitDefinitions/ElectricCurrentGradient.json +++ b/Common/UnitDefinitions/ElectricCurrentGradient.json @@ -15,7 +15,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["A/s"] + "Abbreviations": [ "A/s" ] } ] } diff --git a/Common/UnitDefinitions/ElectricField.json b/Common/UnitDefinitions/ElectricField.json index 1014a1b1c7..3a806fd98b 100644 --- a/Common/UnitDefinitions/ElectricField.json +++ b/Common/UnitDefinitions/ElectricField.json @@ -1,8 +1,7 @@ { "Name": "ElectricField", "BaseUnit": "VoltPerMeter", - "XmlDoc": - "An electric field is a force field that surrounds electric charges that attracts or repels other electric charges.", + "XmlDoc": "An electric field is a force field that surrounds electric charges that attracts or repels other electric charges.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electric_field", "BaseDimensions": { "L": 1, @@ -25,7 +24,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["V/m"] + "Abbreviations": [ "V/m" ] } ] } diff --git a/Common/UnitDefinitions/ElectricInductance.json b/Common/UnitDefinitions/ElectricInductance.json index a7c5a99b37..90df93bead 100644 --- a/Common/UnitDefinitions/ElectricInductance.json +++ b/Common/UnitDefinitions/ElectricInductance.json @@ -15,11 +15,11 @@ "PluralName": "Henries", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli"], + "Prefixes": [ "Nano", "Micro", "Milli" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["H"] + "Abbreviations": [ "H" ] } ] } diff --git a/Common/UnitDefinitions/ElectricPotential.json b/Common/UnitDefinitions/ElectricPotential.json index 23d471b5b3..b1177e4442 100644 --- a/Common/UnitDefinitions/ElectricPotential.json +++ b/Common/UnitDefinitions/ElectricPotential.json @@ -1,8 +1,7 @@ { "Name": "ElectricPotential", "BaseUnit": "Volt", - "XmlDoc": - "In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point.", + "XmlDoc": "In classical electromagnetism, the electric potential (a scalar quantity denoted by Φ, ΦE or V and also called the electric field potential or the electrostatic potential) at a point is the amount of electric potential energy that a unitary point charge would have when located at that point.", "BaseDimensions": { "L": 2, "M": 1, @@ -21,15 +20,15 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Micro", "Milli", "Kilo", "Mega"], + "Prefixes": [ "Micro", "Milli", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["V"] + "Abbreviations": [ "V" ] }, { "Culture": "ru-RU", - "Abbreviations": ["В"] + "Abbreviations": [ "В" ] } ] } diff --git a/Common/UnitDefinitions/ElectricPotentialAc.json b/Common/UnitDefinitions/ElectricPotentialAc.json index e6cce8b6e1..d5835f95ed 100644 --- a/Common/UnitDefinitions/ElectricPotentialAc.json +++ b/Common/UnitDefinitions/ElectricPotentialAc.json @@ -8,11 +8,11 @@ "PluralName": "VoltsAc", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Micro", "Milli", "Kilo", "Mega"], + "Prefixes": [ "Micro", "Milli", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Vac"] + "Abbreviations": [ "Vac" ] } ] } diff --git a/Common/UnitDefinitions/ElectricPotentialDc.json b/Common/UnitDefinitions/ElectricPotentialDc.json index 648026ed69..80c9f71e31 100644 --- a/Common/UnitDefinitions/ElectricPotentialDc.json +++ b/Common/UnitDefinitions/ElectricPotentialDc.json @@ -8,11 +8,11 @@ "PluralName": "VoltsDc", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Micro", "Milli", "Kilo", "Mega"], + "Prefixes": [ "Micro", "Milli", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Vdc"] + "Abbreviations": [ "Vdc" ] } ] } diff --git a/Common/UnitDefinitions/ElectricResistance.json b/Common/UnitDefinitions/ElectricResistance.json index 88fad97d1b..247c810824 100644 --- a/Common/UnitDefinitions/ElectricResistance.json +++ b/Common/UnitDefinitions/ElectricResistance.json @@ -1,8 +1,7 @@ { "Name": "ElectricResistance", "BaseUnit": "Ohm", - "XmlDoc": - "The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor.", + "XmlDoc": "The electrical resistance of an electrical conductor is the opposition to the passage of an electric current through that conductor.", "BaseDimensions": { "L": 2, "M": 1, @@ -15,11 +14,11 @@ "PluralName": "Ohms", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Milli", "Kilo", "Mega", "Giga"], + "Prefixes": [ "Milli", "Kilo", "Mega", "Giga"], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Ω"] + "Abbreviations": [ "Ω" ] } ] } diff --git a/Common/UnitDefinitions/ElectricResistivity.json b/Common/UnitDefinitions/ElectricResistivity.json index 3ad3db29af..8ebbd8419f 100644 --- a/Common/UnitDefinitions/ElectricResistivity.json +++ b/Common/UnitDefinitions/ElectricResistivity.json @@ -1,8 +1,7 @@ { "Name": "ElectricResistivity", "BaseUnit": "OhmMeter", - "XmlDoc": - "Electrical resistivity (also known as resistivity, specific electrical resistance, or volume resistivity) is a fundamental property that quantifies how strongly a given material opposes the flow of electric current.", + "XmlDoc": "Electrical resistivity (also known as resistivity, specific electrical resistance, or volume resistivity) is a fundamental property that quantifies how strongly a given material opposes the flow of electric current.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity", "BaseDimensions": { "L": 3, @@ -16,11 +15,11 @@ "PluralName": "OhmMeters", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Kilo", "Mega"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Ω·m"] + "Abbreviations": [ "Ω·m" ] } ] }, @@ -29,11 +28,11 @@ "PluralName": "OhmsCentimeter", "FromUnitToBaseFunc": "x/100", "FromBaseToUnitFunc": "x*100", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Kilo", "Mega"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Ω·cm"] + "Abbreviations": [ "Ω·cm" ] } ] } diff --git a/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json b/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json index 6816fc4dcd..3528f3c2cd 100644 --- a/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json +++ b/Common/UnitDefinitions/ElectricSurfaceChargeDensity.json @@ -1,8 +1,7 @@ { "Name": "ElectricSurfaceChargeDensity", "BaseUnit": "CoulombPerSquareMeter", - "XmlDoc": - "In electromagnetism, surface charge density is a measure of the amount of electric charge per surface area.", + "XmlDoc": "In electromagnetism, surface charge density is a measure of the amount of electric charge per surface area.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Charge_density", "BaseDimensions": { "L": -2, @@ -23,7 +22,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["C/m²"] + "Abbreviations": [ "C/m²" ] } ] }, @@ -40,7 +39,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["C/cm²"] + "Abbreviations": [ "C/cm²" ] } ] }, @@ -57,7 +56,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["C/in²"] + "Abbreviations": [ "C/in²" ] } ] } diff --git a/Common/UnitDefinitions/Energy.json b/Common/UnitDefinitions/Energy.json index 75547d0dcf..ec0b75e657 100644 --- a/Common/UnitDefinitions/Energy.json +++ b/Common/UnitDefinitions/Energy.json @@ -1,8 +1,7 @@ { "Name": "Energy", "BaseUnit": "Joule", - "XmlDoc": - "The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used.", + "XmlDoc": "The joule, symbol J, is a derived unit of energy, work, or amount of heat in the International System of Units. It is equal to the energy transferred (or work done) when applying a force of one newton through a distance of one metre (1 newton metre or N·m), or in passing an electric current of one ampere through a resistance of one ohm for one second. Many other units of energy are included. Please do not confuse this definition of the calorie with the one colloquially used by the food industry, the large calorie, which is equivalent to 1 kcal. Thermochemical definition of the calorie is used. For BTU, the IT definition is used.", "BaseDimensions": { "L": 2, "M": 1, @@ -19,11 +18,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Milli", "Kilo", "Mega", "Giga"], + "Prefixes": [ "Milli", "Kilo", "Mega", "Giga" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J"] + "Abbreviations": [ "J" ] } ] }, @@ -32,11 +31,11 @@ "PluralName": "Calories", "FromUnitToBaseFunc": "x*4.184", "FromBaseToUnitFunc": "x/4.184", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cal"] + "Abbreviations": [ "cal" ] } ] }, @@ -45,11 +44,11 @@ "PluralName": "BritishThermalUnits", "FromUnitToBaseFunc": "x*1055.05585262", "FromBaseToUnitFunc": "x/1055.05585262", - "Prefixes": ["Kilo", "Mega", "Giga"], + "Prefixes": [ "Kilo", "Mega", "Giga" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["BTU"] + "Abbreviations": [ "BTU" ] } ] }, @@ -61,7 +60,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["eV"] + "Abbreviations": [ "eV" ] } ] }, @@ -73,7 +72,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft·lb"] + "Abbreviations": [ "ft·lb" ] } ] }, @@ -85,7 +84,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["erg"] + "Abbreviations": [ "erg" ] } ] }, @@ -94,15 +93,15 @@ "PluralName": "WattHours", "FromUnitToBaseFunc": "x*3600d", "FromBaseToUnitFunc": "x/3600d", - "Prefixes": ["Kilo", "Mega", "Giga", "Tera"], + "Prefixes": [ "Kilo", "Mega", "Giga", "Tera" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Wh"] + "Abbreviations": [ "Wh" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Вт/ч"] + "Abbreviations": [ "Вт/ч" ] } ] }, @@ -111,16 +110,16 @@ "PluralName": "ThermsEc", "FromUnitToBaseFunc": "x*1.05505585262e8", "FromBaseToUnitFunc": "x/1.05505585262e8", - "Prefixes": ["Deca"], + "Prefixes": [ "Deca" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["th (E.C.)"], + "Abbreviations": [ "th (E.C.)" ], "AbbreviationsForPrefixes": { "Deca": "Dth (E.C.)" } }, { "Culture": "ru-RU", - "Abbreviations": ["Европейский терм"], + "Abbreviations": [ "Европейский терм" ], "AbbreviationsForPrefixes": { "Deca": "Европейский декатерм" } } ] @@ -130,16 +129,16 @@ "PluralName": "ThermsUs", "FromUnitToBaseFunc": "x*1.054804e8", "FromBaseToUnitFunc": "x/1.054804e8", - "Prefixes": ["Deca"], + "Prefixes": [ "Deca" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["th (U.S.)"], + "Abbreviations": [ "th (U.S.)" ], "AbbreviationsForPrefixes": { "Deca": "Dth (U.S.)" } }, { "Culture": "ru-RU", - "Abbreviations": ["Американский терм"], + "Abbreviations": [ "Американский терм" ], "AbbreviationsForPrefixes": { "Deca": "Американский декатерм" } } ] @@ -149,19 +148,19 @@ "PluralName": "ThermsImperial", "FromUnitToBaseFunc": "x*1.05505585257348e8", "FromBaseToUnitFunc": "x/1.05505585257348e8", - "Prefixes": ["Deca"], + "Prefixes": [ "Deca" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["th (imp.)"], + "Abbreviations": [ "th (imp.)" ], "AbbreviationsForPrefixes": { "Deca": "Dth (imp.)" } }, { "Culture": "ru-RU", - "Abbreviations": ["Английский терм"], + "Abbreviations": [ "Английский терм" ], "AbbreviationsForPrefixes": { "Deca": "Английский декатерм" } } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/Entropy.json b/Common/UnitDefinitions/Entropy.json index 4ebd3429f7..c723e866c0 100644 --- a/Common/UnitDefinitions/Entropy.json +++ b/Common/UnitDefinitions/Entropy.json @@ -1,8 +1,7 @@ { "Name": "Entropy", "BaseUnit": "JoulePerKelvin", - "XmlDoc": - "Entropy is an important concept in the branch of science known as thermodynamics. The idea of \"irreversibility\" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units", + "XmlDoc": "Entropy is an important concept in the branch of science known as thermodynamics. The idea of \"irreversibility\" is central to the understanding of entropy. It is often said that entropy is an expression of the disorder, or randomness of a system, or of our lack of information about it. Entropy is an extensive property. It has the dimension of energy divided by temperature, which has a unit of joules per kelvin (J/K) in the International System of Units", "BaseDimensions": { "L": 2, "M": 1, @@ -15,11 +14,11 @@ "PluralName": "JoulesPerKelvin", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/K"] + "Abbreviations": [ "J/K" ] } ] }, @@ -28,11 +27,11 @@ "PluralName": "CaloriesPerKelvin", "FromUnitToBaseFunc": "x*4.184", "FromBaseToUnitFunc": "x/4.184", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cal/K"] + "Abbreviations": [ "cal/K" ] } ] }, @@ -41,13 +40,13 @@ "PluralName": "JoulesPerDegreeCelsius", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/C"] + "Abbreviations": [ "J/C" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/Force.json b/Common/UnitDefinitions/Force.json index 0594836042..aebf6a9ed9 100644 --- a/Common/UnitDefinitions/Force.json +++ b/Common/UnitDefinitions/Force.json @@ -1,8 +1,7 @@ { "Name": "Force", "BaseUnit": "Newton", - "XmlDoc": - "In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F.", + "XmlDoc": "In physics, a force is any influence that causes an object to undergo a certain change, either concerning its movement, direction, or geometrical construction. In other words, a force can cause an object with mass to change its velocity (which includes to begin moving from a state of rest), i.e., to accelerate, or a flexible object to deform, or both. Force can also be described by intuitive concepts such as a push or a pull. A force has both magnitude and direction, making it a vector quantity. It is measured in the SI unit of newtons and represented by the symbol F.", "BaseDimensions": { "L": 1, "M": 1, @@ -22,11 +21,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dyn"] + "Abbreviations": [ "dyn" ] }, { "Culture": "ru-RU", - "Abbreviations": ["дин"] + "Abbreviations": [ "дин" ] } ] }, @@ -38,11 +37,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf"] + "Abbreviations": [ "kgf" ] }, { "Culture": "ru-RU", - "Abbreviations": ["кгс"] + "Abbreviations": [ "кгс" ] } ] }, @@ -54,11 +53,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Ton"] + "Abbreviations": [ "Ton" ] }, { "Culture": "ru-RU", - "Abbreviations": ["тс"] + "Abbreviations": [ "тс" ] } ] }, @@ -72,15 +71,15 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Micro", "Milli", "Deca", "Kilo", "Mega"], + "Prefixes": [ "Micro", "Milli", "Deca", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N"] + "Abbreviations": [ "N" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Н"] + "Abbreviations": [ "Н" ] } ] }, @@ -92,11 +91,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kp"] + "Abbreviations": [ "kp" ] }, { "Culture": "ru-RU", - "Abbreviations": ["кгс"] + "Abbreviations": [ "кгс" ] } ] }, @@ -113,11 +112,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["pdl"] + "Abbreviations": [ "pdl" ] }, { "Culture": "ru-RU", - "Abbreviations": ["паундаль"] + "Abbreviations": [ "паундаль" ] } ] }, @@ -129,11 +128,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf"] + "Abbreviations": [ "lbf" ] }, { "Culture": "ru-RU", - "Abbreviations": ["фунт-сила"] + "Abbreviations": [ "фунт-сила" ] } ] }, @@ -145,9 +144,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ozf"] + "Abbreviations": [ "ozf" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/ForceChangeRate.json b/Common/UnitDefinitions/ForceChangeRate.json index 3442d4d597..f6969c638f 100644 --- a/Common/UnitDefinitions/ForceChangeRate.json +++ b/Common/UnitDefinitions/ForceChangeRate.json @@ -1,8 +1,7 @@ { "Name": "ForceChangeRate", "BaseUnit": "NewtonPerSecond", - "XmlDoc": - "Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time).", + "XmlDoc": "Force change rate is the ratio of the force change to the time during which the change occurred (value of force changes per unit time).", "BaseDimensions": { "L": 1, "M": 1, @@ -14,11 +13,11 @@ "PluralName": "NewtonsPerMinute", "FromUnitToBaseFunc": "x/60", "FromBaseToUnitFunc": "x*60", - "Prefixes": ["Deca", "Kilo"], + "Prefixes": [ "Deca", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N/min"] + "Abbreviations": [ "N/min" ] } ] }, @@ -27,11 +26,11 @@ "PluralName": "NewtonsPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N/s"] + "Abbreviations": [ "N/s" ] } ] } diff --git a/Common/UnitDefinitions/ForcePerLength.json b/Common/UnitDefinitions/ForcePerLength.json index 1281d1397c..fa587153e2 100644 --- a/Common/UnitDefinitions/ForcePerLength.json +++ b/Common/UnitDefinitions/ForcePerLength.json @@ -12,11 +12,11 @@ "PluralName": "NewtonsPerMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N/m"] + "Abbreviations": [ "N/m" ] } ] }, @@ -28,11 +28,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf/m"] + "Abbreviations": [ "kgf/m" ] }, { "Culture": "ru-RU", - "Abbreviations": ["кгс/м"] + "Abbreviations": [ "кгс/м" ] } ] }, @@ -44,7 +44,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf/ft"] + "Abbreviations": [ "lbf/ft" ] } ] }, @@ -56,7 +56,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf/in"] + "Abbreviations": [ "lbf/in" ] } ] }, @@ -68,7 +68,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf/yd"] + "Abbreviations": [ "lbf/yd" ] } ] } diff --git a/Common/UnitDefinitions/Frequency.json b/Common/UnitDefinitions/Frequency.json index 8acbfc4d18..9d60cdd35e 100644 --- a/Common/UnitDefinitions/Frequency.json +++ b/Common/UnitDefinitions/Frequency.json @@ -11,11 +11,11 @@ "PluralName": "Hertz", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega", "Giga", "Tera"], + "Prefixes": [ "Kilo", "Mega", "Giga", "Tera" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Hz"] + "Abbreviations": [ "Hz" ] } ] }, @@ -28,7 +28,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["rad/s"] + "Abbreviations": [ "rad/s" ] } ] }, @@ -40,7 +40,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cpm"] + "Abbreviations": [ "cpm" ] } ] }, @@ -52,7 +52,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cph"] + "Abbreviations": [ "cph" ] } ] }, @@ -64,9 +64,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bpm"] + "Abbreviations": [ "bpm" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/FuelEfficiency.json b/Common/UnitDefinitions/FuelEfficiency.json index 830c5eab42..2da60218f7 100644 --- a/Common/UnitDefinitions/FuelEfficiency.json +++ b/Common/UnitDefinitions/FuelEfficiency.json @@ -1,65 +1,55 @@ { - "Name": "FuelEfficiency", - "BaseUnit": "LiterPer100Kilometers", - "XmlDoc": - "Fuel efficiency is a form of thermal efficiency, meaning the ratio from effort to result of a process that converts chemical potential energy contained in a carrier (fuel) into kinetic energy or work. Fuel economy is stated as \"fuel consumption\" in liters per 100 kilometers (L/100 km). In countries using non-metric system, fuel economy is expressed in miles per gallon (mpg) (imperial galon or US galon).", - "XmlDocRemarks": "https://en.wikipedia.org/wiki/Fuel_efficiency", - "Units": [ - { - "SingularName": "LiterPer100Kilometers", - "PluralName": "LitersPer100Kilometers", - "FromUnitToBaseFunc": "x", - "FromBaseToUnitFunc": "x", - "Localization": [ - { + "Name": "FuelEfficiency", + "BaseUnit": "LiterPer100Kilometers", + "XmlDoc": "Fuel efficiency is a form of thermal efficiency, meaning the ratio from effort to result of a process that converts chemical potential energy contained in a carrier (fuel) into kinetic energy or work. Fuel economy is stated as \"fuel consumption\" in liters per 100 kilometers (L/100 km). In countries using non-metric system, fuel economy is expressed in miles per gallon (mpg) (imperial galon or US galon).", + "XmlDocRemarks": "https://en.wikipedia.org/wiki/Fuel_efficiency", + "Units": [{ + "SingularName": "LiterPer100Kilometers", + "PluralName": "LitersPer100Kilometers", + "FromUnitToBaseFunc": "x", + "FromBaseToUnitFunc": "x", + "Localization": [{ "Culture": "en-US", "Abbreviations": [ "L/100km" ] - } - ] - }, - { - "SingularName": "MilePerUsGallon", - "PluralName": "MilesPerUsGallon", - "FromUnitToBaseFunc": "(100*3.785411784)/(1.609344*x)", - "FromBaseToUnitFunc": "(100*3.785411784)/(1.609344*x)", - "Localization": [ - { + }] + }, + { + "SingularName": "MilePerUsGallon", + "PluralName": "MilesPerUsGallon", + "FromUnitToBaseFunc": "(100*3.785411784)/(1.609344*x)", + "FromBaseToUnitFunc": "(100*3.785411784)/(1.609344*x)", + "Localization": [{ "Culture": "en-US", "Abbreviations": [ "mpg (U.S.)" ] - } - ] - }, - { - "SingularName": "MilePerUkGallon", - "PluralName": "MilesPerUkGallon", - "FromUnitToBaseFunc": "(100*4.54609188)/(1.609344*x)", - "FromBaseToUnitFunc": "(100*4.54609188)/(1.609344*x)", - "Localization": [ - { + }] + }, + { + "SingularName": "MilePerUkGallon", + "PluralName": "MilesPerUkGallon", + "FromUnitToBaseFunc": "(100*4.54609188)/(1.609344*x)", + "FromBaseToUnitFunc": "(100*4.54609188)/(1.609344*x)", + "Localization": [{ "Culture": "en-US", "Abbreviations": [ "mpg (imp.)" ] - } - ] - }, - { - "SingularName": "KilometerPerLiter", - "PluralName": "KilometersPerLiters", - "FromUnitToBaseFunc": "100/x", - "FromBaseToUnitFunc": "100/x", - "Localization": [ - { + }] + }, + { + "SingularName": "KilometerPerLiter", + "PluralName": "KilometersPerLiters", + "FromUnitToBaseFunc": "100/x", + "FromBaseToUnitFunc": "100/x", + "Localization": [{ "Culture": "en-US", "Abbreviations": [ "km/L" ] - } - ] - } - ] -} \ No newline at end of file + }] + } + ] + } \ No newline at end of file diff --git a/Common/UnitDefinitions/HeatFlux.json b/Common/UnitDefinitions/HeatFlux.json index 945bf0b079..aaa1658ef9 100644 --- a/Common/UnitDefinitions/HeatFlux.json +++ b/Common/UnitDefinitions/HeatFlux.json @@ -16,11 +16,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/m²"] + "Abbreviations": [ "W/m²" ] } ] }, @@ -32,7 +32,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/in²"] + "Abbreviations": [ "W/in²" ] } ] }, @@ -44,7 +44,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/ft²"] + "Abbreviations": [ "W/ft²" ] } ] }, @@ -56,7 +56,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["BTU/s·in²"] + "Abbreviations": [ "BTU/s·in²" ] } ] }, @@ -68,7 +68,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["BTU/s·ft²"] + "Abbreviations": [ "BTU/s·ft²" ] } ] }, @@ -80,7 +80,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["BTU/min·ft²"] + "Abbreviations": [ "BTU/min·ft²" ] } ] }, @@ -92,7 +92,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["BTU/h·ft²"] + "Abbreviations": [ "BTU/h·ft²" ] } ] }, @@ -101,11 +101,11 @@ "PluralName": "CaloriesPerSecondSquareCentimeter", "FromUnitToBaseFunc": "x*4.1868e4", "FromBaseToUnitFunc": "x/4.1868e4", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cal/s·cm²"] + "Abbreviations": [ "cal/s·cm²" ] } ] }, @@ -117,7 +117,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kcal/h·m²"] + "Abbreviations": [ "kcal/h·m²" ] } ] }, @@ -129,7 +129,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf/(ft·s)"] + "Abbreviations": [ "lbf/(ft·s)" ] } ] }, @@ -141,7 +141,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/s³", "lbm/s³"] + "Abbreviations": [ "lb/s³", "lbm/s³" ] } ] } diff --git a/Common/UnitDefinitions/HeatTransferCoefficient.json b/Common/UnitDefinitions/HeatTransferCoefficient.json index 660b1f86de..97220b1efa 100644 --- a/Common/UnitDefinitions/HeatTransferCoefficient.json +++ b/Common/UnitDefinitions/HeatTransferCoefficient.json @@ -1,8 +1,7 @@ { "Name": "HeatTransferCoefficient", "BaseUnit": "WattPerSquareMeterKelvin", - "XmlDoc": - "The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT)", + "XmlDoc": "The heat transfer coefficient or film coefficient, or film effectiveness, in thermodynamics and in mechanics is the proportionality constant between the heat flux and the thermodynamic driving force for the flow of heat (i.e., the temperature difference, ΔT)", "BaseDimensions": { "M": 1, "T": -3, @@ -17,7 +16,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/m²·K"] + "Abbreviations": [ "W/m²·K" ] } ] }, @@ -29,7 +28,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/m²·°C"] + "Abbreviations": [ "W/m²·°C" ] } ] }, @@ -41,7 +40,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Btu/ft²·hr·°F"] + "Abbreviations": [ "Btu/ft²·hr·°F" ] } ] } diff --git a/Common/UnitDefinitions/Illuminance.json b/Common/UnitDefinitions/Illuminance.json index 45dc02bdd9..c5fc7f0b08 100644 --- a/Common/UnitDefinitions/Illuminance.json +++ b/Common/UnitDefinitions/Illuminance.json @@ -13,11 +13,11 @@ "PluralName": "Lux", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Milli", "Kilo", "Mega"], + "Prefixes": [ "Milli", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lx"] + "Abbreviations": [ "lx" ] } ] } diff --git a/Common/UnitDefinitions/Information.json b/Common/UnitDefinitions/Information.json index c521b6b631..7c28cad347 100644 --- a/Common/UnitDefinitions/Information.json +++ b/Common/UnitDefinitions/Information.json @@ -2,19 +2,18 @@ "Name": "Information", "BaseUnit": "Bit", "BaseType": "decimal", - "XmlDoc": - "In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables.", + "XmlDoc": "In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables.", "Units": [ { "SingularName": "Byte", "PluralName": "Bytes", "FromUnitToBaseFunc": "x*8m", "FromBaseToUnitFunc": "x/8m", - "Prefixes": ["Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi"], + "Prefixes": [ "Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["B"] + "Abbreviations": [ "B" ] } ] }, @@ -23,11 +22,11 @@ "PluralName": "Bits", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi"], + "Prefixes": [ "Kilo", "Mega", "Giga", "Tera", "Peta", "Exa", "Kibi", "Mebi", "Gibi", "Tebi", "Pebi", "Exbi" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["b"] + "Abbreviations": [ "b" ] } ] } diff --git a/Common/UnitDefinitions/Irradiance.json b/Common/UnitDefinitions/Irradiance.json index c47152d9bd..0c3bfd7a3a 100644 --- a/Common/UnitDefinitions/Irradiance.json +++ b/Common/UnitDefinitions/Irradiance.json @@ -12,11 +12,11 @@ "PluralName": "WattsPerSquareMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Kilo", "Mega"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/m²"] + "Abbreviations": [ "W/m²" ] } ] }, @@ -25,11 +25,11 @@ "PluralName": "WattsPerSquareCentimeter", "FromUnitToBaseFunc": "x*10000", "FromBaseToUnitFunc": "x*0.0001", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Kilo", "Mega"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/cm²"] + "Abbreviations": [ "W/cm²" ] } ] } diff --git a/Common/UnitDefinitions/Irradiation.json b/Common/UnitDefinitions/Irradiation.json index 0318fa3983..4d6617a85a 100644 --- a/Common/UnitDefinitions/Irradiation.json +++ b/Common/UnitDefinitions/Irradiation.json @@ -1,8 +1,7 @@ { "Name": "Irradiation", "BaseUnit": "JoulePerSquareMeter", - "XmlDoc": - "Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources.", + "XmlDoc": "Irradiation is the process by which an object is exposed to radiation. The exposure can originate from various sources, including natural sources.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Irradiation", "BaseDimensions": { "M": 1, @@ -14,11 +13,11 @@ "PluralName": "JoulesPerSquareMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/m²"] + "Abbreviations": [ "J/m²" ] } ] }, @@ -27,11 +26,11 @@ "PluralName": "JoulesPerSquareCentimeter", "FromUnitToBaseFunc": "x*1e4", "FromBaseToUnitFunc": "x/1e4", - "Prefixes": ["Milli"], + "Prefixes": [ "Milli" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/cm²"] + "Abbreviations": [ "J/cm²" ] } ] }, @@ -43,7 +42,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/mm²"] + "Abbreviations": [ "J/mm²" ] } ] }, @@ -52,11 +51,11 @@ "PluralName": "WattHoursPerSquareMeter", "FromUnitToBaseFunc": "x*3600d", "FromBaseToUnitFunc": "x/3600d", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Wh/m²"] + "Abbreviations": [ "Wh/m²" ] } ] } diff --git a/Common/UnitDefinitions/KinematicViscosity.json b/Common/UnitDefinitions/KinematicViscosity.json index 14e27ded57..c4d1d07bb5 100644 --- a/Common/UnitDefinitions/KinematicViscosity.json +++ b/Common/UnitDefinitions/KinematicViscosity.json @@ -1,8 +1,7 @@ { "Name": "KinematicViscosity", "BaseUnit": "SquareMeterPerSecond", - "XmlDoc": - "The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress.", + "XmlDoc": "The viscosity of a fluid is a measure of its resistance to gradual deformation by shear stress or tensile stress.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Viscosity", "BaseDimensions": { "L": 2, @@ -17,11 +16,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m²/s"] + "Abbreviations": [ "m²/s" ] }, { "Culture": "ru-RU", - "Abbreviations": ["м²/с"] + "Abbreviations": [ "м²/с" ] } ] }, @@ -30,17 +29,17 @@ "PluralName": "Stokes", "FromUnitToBaseFunc": "x/1e4", "FromBaseToUnitFunc": "x*1e4", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["St"] + "Abbreviations": [ "St" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Ст"] + "Abbreviations": [ "Ст" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/LapseRate.json b/Common/UnitDefinitions/LapseRate.json index e2ae25f8eb..782eec865b 100644 --- a/Common/UnitDefinitions/LapseRate.json +++ b/Common/UnitDefinitions/LapseRate.json @@ -1,8 +1,7 @@ { "Name": "LapseRate", "BaseUnit": "DegreeCelsiusPerKilometer", - "XmlDoc": - "Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude.", + "XmlDoc": "Lapse rate is the rate at which Earth's atmospheric temperature decreases with an increase in altitude, or increases with the decrease in altitude.", "BaseDimensions": { "L": -1, "Θ": 1 @@ -16,7 +15,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["∆°C/km"] + "Abbreviations": [ "∆°C/km" ] } ] } diff --git a/Common/UnitDefinitions/Length.json b/Common/UnitDefinitions/Length.json index 7034622490..de016ce60e 100644 --- a/Common/UnitDefinitions/Length.json +++ b/Common/UnitDefinitions/Length.json @@ -1,8 +1,7 @@ { "Name": "Length", "BaseUnit": "Meter", - "XmlDoc": - "Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units.", + "XmlDoc": "Many different units of length have been used around the world. The main units in modern use are U.S. customary units in the United States and the Metric system elsewhere. British Imperial units are still used for some purposes in the United Kingdom and some other countries. The metric system is sub-divided into SI and non-SI units.", "BaseDimensions": { "L": 1 }, @@ -15,15 +14,15 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Hecto", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Hecto", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m"] + "Abbreviations": [ "m" ] }, { "Culture": "ru-RU", - "Abbreviations": ["м"] + "Abbreviations": [ "м" ] } ] }, @@ -38,11 +37,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mi"] + "Abbreviations": [ "mi" ] }, { "Culture": "ru-RU", - "Abbreviations": ["миля"] + "Abbreviations": [ "миля" ] } ] }, @@ -57,11 +56,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["yd"] + "Abbreviations": [ "yd" ] }, { "Culture": "ru-RU", - "Abbreviations": ["ярд"] + "Abbreviations": [ "ярд" ] } ] }, @@ -76,11 +75,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft", "'", "′"] + "Abbreviations": [ "ft", "'", "′" ] }, { "Culture": "ru-RU", - "Abbreviations": ["фут"] + "Abbreviations": [ "фут" ] } ] }, @@ -95,7 +94,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ftUS"] + "Abbreviations": [ "ftUS" ] } ] }, @@ -110,11 +109,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["in", "\\\"", "″"] + "Abbreviations": [ "in", "\\\"", "″" ] }, { "Culture": "ru-RU", - "Abbreviations": ["дюйм"] + "Abbreviations": [ "дюйм" ] } ] }, @@ -129,11 +128,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mil"] + "Abbreviations": [ "mil" ] }, { "Culture": "ru-RU", - "Abbreviations": ["мил"] + "Abbreviations": [ "мил" ] } ] }, @@ -148,11 +147,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["NM"] + "Abbreviations": [ "NM" ] }, { "Culture": "ru-RU", - "Abbreviations": ["мил"] + "Abbreviations": [ "мил" ] } ] }, @@ -167,7 +166,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["fathom"] + "Abbreviations": [ "fathom" ] } ] }, @@ -182,7 +181,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["shackle"] + "Abbreviations": [ "shackle" ] } ] }, @@ -197,11 +196,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["µin"] + "Abbreviations": [ "µin" ] }, { "Culture": "ru-RU", - "Abbreviations": ["микродюйм"] + "Abbreviations": [ "микродюйм" ] } ] }, @@ -216,7 +215,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["pt"] + "Abbreviations": [ "pt" ] } ] }, @@ -231,7 +230,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["pt"] + "Abbreviations": [ "pt" ] } ] }, @@ -246,7 +245,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["pica"] + "Abbreviations": [ "pica" ] } ] }, @@ -261,7 +260,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["pica"] + "Abbreviations": [ "pica" ] } ] }, @@ -276,7 +275,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["twip"] + "Abbreviations": [ "twip" ] } ] }, @@ -291,7 +290,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["h", "hh"] + "Abbreviations": [ "h", "hh" ] } ] }, @@ -305,7 +304,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["au", "ua"] + "Abbreviations": [ "au", "ua" ] } ] }, @@ -314,14 +313,13 @@ "PluralName": "Parsecs", "FromUnitToBaseFunc": "x * 3.08567758128e16", "FromBaseToUnitFunc": "x / 3.08567758128e16", - "XmlDocSummary": - "A parsec is defined as the distance at which one astronomical unit (AU) subtends an angle of one arcsecond.", + "XmlDocSummary": "A parsec is defined as the distance at which one astronomical unit (AU) subtends an angle of one arcsecond.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Parsec", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["pc"] + "Abbreviations": [ "pc" ] } ] }, @@ -332,11 +330,11 @@ "FromBaseToUnitFunc": "x / 9.46073047258e15", "XmlDocSummary": "A Light Year (ly) is the distance that light travel during an Earth year, ie 365 days.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Light-year", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ly"] + "Abbreviations": [ "ly" ] } ] }, @@ -350,9 +348,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["R⊙"] + "Abbreviations": [ "R⊙" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/Level.json b/Common/UnitDefinitions/Level.json index b8e51ae572..f014fcb2eb 100644 --- a/Common/UnitDefinitions/Level.json +++ b/Common/UnitDefinitions/Level.json @@ -3,8 +3,7 @@ "BaseUnit": "Decibel", "Logarithmic": "True", "LogarithmicScalingFactor": "1", - "XmlDoc": - "Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units.", + "XmlDoc": "Level is the logarithm of the ratio of a quantity Q to a reference value of that quantity, Q₀, expressed in dimensionless units.", "Units": [ { "SingularName": "Decibel", @@ -14,7 +13,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dB"] + "Abbreviations": [ "dB" ] } ] }, @@ -26,7 +25,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Np"] + "Abbreviations": [ "Np" ] } ] } diff --git a/Common/UnitDefinitions/LinearDensity.json b/Common/UnitDefinitions/LinearDensity.json index d85ba98de7..ab068224b6 100644 --- a/Common/UnitDefinitions/LinearDensity.json +++ b/Common/UnitDefinitions/LinearDensity.json @@ -1,8 +1,7 @@ { "Name": "LinearDensity", "BaseUnit": "KilogramPerMeter", - "XmlDoc": - "The Linear Density, or more precisely, the linear mass density, of a substance is its mass per unit length. The term linear density is most often used when describing the characteristics of one-dimensional objects, although linear density can also be used to describe the density of a three-dimensional quantity along one particular dimension.", + "XmlDoc": "The Linear Density, or more precisely, the linear mass density, of a substance is its mass per unit length. The term linear density is most often used when describing the characteristics of one-dimensional objects, although linear density can also be used to describe the density of a three-dimensional quantity along one particular dimension.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Linear_density", "BaseDimensions": { "L": -1, @@ -14,11 +13,11 @@ "PluralName": "GramsPerMeter", "FromUnitToBaseFunc": "x*1e-3", "FromBaseToUnitFunc": "x/1e-3", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/m"] + "Abbreviations": [ "g/m" ] } ] }, @@ -30,7 +29,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/ft"] + "Abbreviations": [ "lb/ft" ] } ] } diff --git a/Common/UnitDefinitions/Luminosity.json b/Common/UnitDefinitions/Luminosity.json index 005e7b6521..59a1d82efd 100644 --- a/Common/UnitDefinitions/Luminosity.json +++ b/Common/UnitDefinitions/Luminosity.json @@ -2,8 +2,7 @@ "Name": "Luminosity", "BaseUnit": "Watt", "BaseType": "double", - "XmlDoc": - "Luminosity is an absolute measure of radiated electromagnetic power (light), the radiant power emitted by a light-emitting object.", + "XmlDoc": "Luminosity is an absolute measure of radiated electromagnetic power (light), the radiant power emitted by a light-emitting object.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Luminosity", "BaseDimensions": { "L": 2, @@ -16,11 +15,11 @@ "PluralName": "Watts", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Femto", "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera", "Peta"], + "Prefixes": [ "Femto", "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera", "Peta" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W"] + "Abbreviations": [ "W" ] } ] }, @@ -33,7 +32,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["L⊙"] + "Abbreviations": [ "L⊙" ] } ] } diff --git a/Common/UnitDefinitions/LuminousFlux.json b/Common/UnitDefinitions/LuminousFlux.json index 5bfcbb6bf9..3307cc700c 100644 --- a/Common/UnitDefinitions/LuminousFlux.json +++ b/Common/UnitDefinitions/LuminousFlux.json @@ -15,7 +15,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lm"] + "Abbreviations": [ "lm" ] } ] } diff --git a/Common/UnitDefinitions/LuminousIntensity.json b/Common/UnitDefinitions/LuminousIntensity.json index 173985037c..f32f634628 100644 --- a/Common/UnitDefinitions/LuminousIntensity.json +++ b/Common/UnitDefinitions/LuminousIntensity.json @@ -1,8 +1,7 @@ { "Name": "LuminousIntensity", "BaseUnit": "Candela", - "XmlDoc": - "In photometry, luminous intensity is a measure of the wavelength-weighted power emitted by a light source in a particular direction per unit solid angle, based on the luminosity function, a standardized model of the sensitivity of the human eye.", + "XmlDoc": "In photometry, luminous intensity is a measure of the wavelength-weighted power emitted by a light source in a particular direction per unit solid angle, based on the luminosity function, a standardized model of the sensitivity of the human eye.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Luminous_intensity", "BaseDimensions": { "J": 1 @@ -19,7 +18,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cd"] + "Abbreviations": [ "cd" ] } ] } diff --git a/Common/UnitDefinitions/MagneticField.json b/Common/UnitDefinitions/MagneticField.json index 8aebaebaaf..9eafc9769c 100644 --- a/Common/UnitDefinitions/MagneticField.json +++ b/Common/UnitDefinitions/MagneticField.json @@ -1,8 +1,7 @@ { "Name": "MagneticField", "BaseUnit": "Tesla", - "XmlDoc": - "A magnetic field is a force field that is created by moving electric charges (electric currents) and magnetic dipoles, and exerts a force on other nearby moving charges and magnetic dipoles.", + "XmlDoc": "A magnetic field is a force field that is created by moving electric charges (electric currents) and magnetic dipoles, and exerts a force on other nearby moving charges and magnetic dipoles.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Magnetic_field", "BaseDimensions": { "M": 1, @@ -15,11 +14,11 @@ "PluralName": "Teslas", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli"], + "Prefixes": [ "Nano", "Micro", "Milli" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["T"] + "Abbreviations": [ "T" ] } ] } diff --git a/Common/UnitDefinitions/MagneticFlux.json b/Common/UnitDefinitions/MagneticFlux.json index 9a9a03bd1e..92bb40ce26 100644 --- a/Common/UnitDefinitions/MagneticFlux.json +++ b/Common/UnitDefinitions/MagneticFlux.json @@ -1,8 +1,7 @@ { "Name": "MagneticFlux", "BaseUnit": "Weber", - "XmlDoc": - "In physics, specifically electromagnetism, the magnetic flux through a surface is the surface integral of the normal component of the magnetic field B passing through that surface.", + "XmlDoc": "In physics, specifically electromagnetism, the magnetic flux through a surface is the surface integral of the normal component of the magnetic field B passing through that surface.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Magnetic_flux", "BaseDimensions": { "L": 2, @@ -19,7 +18,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Wb"] + "Abbreviations": [ "Wb" ] } ] } diff --git a/Common/UnitDefinitions/Magnetization.json b/Common/UnitDefinitions/Magnetization.json index 30ba967619..6b15c37a48 100644 --- a/Common/UnitDefinitions/Magnetization.json +++ b/Common/UnitDefinitions/Magnetization.json @@ -1,8 +1,7 @@ { "Name": "Magnetization", "BaseUnit": "AmperePerMeter", - "XmlDoc": - "In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material.", + "XmlDoc": "In classical electromagnetism, magnetization is the vector field that expresses the density of permanent or induced magnetic dipole moments in a magnetic material.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Magnetization", "BaseDimensions": { "L": -1, @@ -21,7 +20,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["A/m"] + "Abbreviations": [ "A/m" ] } ] } diff --git a/Common/UnitDefinitions/Mass.json b/Common/UnitDefinitions/Mass.json index a820435bcf..ab018920e2 100644 --- a/Common/UnitDefinitions/Mass.json +++ b/Common/UnitDefinitions/Mass.json @@ -1,8 +1,7 @@ { "Name": "Mass", "BaseUnit": "Kilogram", - "XmlDoc": - "In physics, mass (from Greek μᾶζα \"barley cake, lump [of dough]\") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg).", + "XmlDoc": "In physics, mass (from Greek μᾶζα \"barley cake, lump [of dough]\") is a property of a physical system or body, giving rise to the phenomena of the body's resistance to being accelerated by a force and the strength of its mutual gravitational attraction with other bodies. Instruments such as mass balances or scales use those phenomena to measure mass. The SI unit of mass is the kilogram (kg).", "BaseDimensions": { "M": 1 }, @@ -15,15 +14,15 @@ }, "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g"] + "Abbreviations": [ "g" ] }, { "Culture": "ru-RU", - "Abbreviations": ["г"] + "Abbreviations": [ "г" ] } ] }, @@ -35,15 +34,15 @@ }, "FromUnitToBaseFunc": "x*1e3", "FromBaseToUnitFunc": "x/1e3", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t"] + "Abbreviations": [ "t" ] }, { "Culture": "ru-RU", - "Abbreviations": ["т"] + "Abbreviations": [ "т" ] } ] }, @@ -55,17 +54,16 @@ }, "FromUnitToBaseFunc": "x*9.0718474e2", "FromBaseToUnitFunc": "x/9.0718474e2", - "XmlDocSummary": - "The short ton is a unit of mass equal to 2,000 pounds (907.18474 kg), that is most commonly used in the United States – known there simply as the ton.", + "XmlDocSummary": "The short ton is a unit of mass equal to 2,000 pounds (907.18474 kg), that is most commonly used in the United States – known there simply as the ton.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Short_ton", "Localization": [ { "Culture": "en-US", - "Abbreviations": ["short tn"] + "Abbreviations": [ "short tn" ] }, { "Culture": "ru-RU", - "Abbreviations": ["тонна малая"] + "Abbreviations": [ "тонна малая" ] } ] }, @@ -77,17 +75,16 @@ }, "FromUnitToBaseFunc": "x*1.0160469088e3", "FromBaseToUnitFunc": "x/1.0160469088e3", - "XmlDocSummary": - "Long ton (weight ton or Imperial ton) is a unit of mass equal to 2,240 pounds (1,016 kg) and is the name for the unit called the \"ton\" in the avoirdupois or Imperial system of measurements that was used in the United Kingdom and several other Commonwealth countries before metrication.", + "XmlDocSummary": "Long ton (weight ton or Imperial ton) is a unit of mass equal to 2,240 pounds (1,016 kg) and is the name for the unit called the \"ton\" in the avoirdupois or Imperial system of measurements that was used in the United Kingdom and several other Commonwealth countries before metrication.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Long_ton", "Localization": [ { "Culture": "en-US", - "Abbreviations": ["long tn"] + "Abbreviations": [ "long tn" ] }, { "Culture": "ru-RU", - "Abbreviations": ["тонна большая"] + "Abbreviations": [ "тонна большая" ] } ] }, @@ -99,17 +96,16 @@ }, "FromUnitToBaseFunc": "x*0.45359237", "FromBaseToUnitFunc": "x/0.45359237", - "XmlDocSummary": - "The pound or pound-mass (abbreviations: lb, lbm) is a unit of mass used in the imperial, United States customary and other systems of measurement. A number of different definitions have been used, the most common today being the international avoirdupois pound which is legally defined as exactly 0.45359237 kilograms, and which is divided into 16 avoirdupois ounces.", - "Prefixes": ["Kilo", "Mega"], + "XmlDocSummary": "The pound or pound-mass (abbreviations: lb, lbm) is a unit of mass used in the imperial, United States customary and other systems of measurement. A number of different definitions have been used, the most common today being the international avoirdupois pound which is legally defined as exactly 0.45359237 kilograms, and which is divided into 16 avoirdupois ounces.", + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb", "lbs", "lbm"] + "Abbreviations": [ "lb", "lbs", "lbm" ] }, { "Culture": "ru-RU", - "Abbreviations": ["фунт"] + "Abbreviations": [ "фунт" ] } ] }, @@ -121,13 +117,12 @@ }, "FromUnitToBaseFunc": "x/35.2739619", "FromBaseToUnitFunc": "x*35.2739619", - "XmlDocSummary": - "An ounce (abbreviated oz) is usually the international avoirdupois ounce as used in the United States customary and British imperial systems, which is equal to one-sixteenth of a pound or approximately 28 grams. The abbreviation 'oz' derives from the Italian word onza (now spelled oncia).", + "XmlDocSummary": "An ounce (abbreviated oz) is usually the international avoirdupois ounce as used in the United States customary and British imperial systems, which is equal to one-sixteenth of a pound or approximately 28 grams. The abbreviation 'oz' derives from the Italian word onza (now spelled oncia).", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Ounce", "Localization": [ { "Culture": "en-US", - "Abbreviations": ["oz"] + "Abbreviations": [ "oz" ] } ] }, @@ -139,13 +134,12 @@ }, "FromUnitToBaseFunc": "x/6.852176556196105e-2", "FromBaseToUnitFunc": "x*6.852176556196105e-2", - "XmlDocSummary": - "The slug (abbreviation slug) is a unit of mass that is accelerated by 1 ft/s² when a force of one pound (lbf) is exerted on it.", + "XmlDocSummary": "The slug (abbreviation slug) is a unit of mass that is accelerated by 1 ft/s² when a force of one pound (lbf) is exerted on it.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Slug_(unit)", "Localization": [ { "Culture": "en-US", - "Abbreviations": ["slug"] + "Abbreviations": [ "slug" ] } ] }, @@ -157,13 +151,12 @@ }, "FromUnitToBaseFunc": "x/0.1574731728702698", "FromBaseToUnitFunc": "x*0.1574731728702698", - "XmlDocSummary": - "The stone (abbreviation st) is a unit of mass equal to 14 pounds avoirdupois (about 6.35 kilograms) used in Great Britain and Ireland for measuring human body weight.", + "XmlDocSummary": "The stone (abbreviation st) is a unit of mass equal to 14 pounds avoirdupois (about 6.35 kilograms) used in Great Britain and Ireland for measuring human body weight.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Stone_(unit)", "Localization": [ { "Culture": "en-US", - "Abbreviations": ["st"] + "Abbreviations": [ "st" ] } ] }, @@ -175,13 +168,12 @@ }, "FromUnitToBaseFunc": "x/0.022046226218487758", "FromBaseToUnitFunc": "x*0.022046226218487758", - "XmlDocSummary": - "The short hundredweight (abbreviation cwt) is a unit of mass equal to 100 pounds in US and Canada. In British English, the short hundredweight is referred to as the \"cental\".", + "XmlDocSummary": "The short hundredweight (abbreviation cwt) is a unit of mass equal to 100 pounds in US and Canada. In British English, the short hundredweight is referred to as the \"cental\".", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Hundredweight", "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cwt"] + "Abbreviations": [ "cwt" ] } ] }, @@ -193,13 +185,12 @@ }, "FromUnitToBaseFunc": "x/0.01968413055222121", "FromBaseToUnitFunc": "x*0.01968413055222121", - "XmlDocSummary": - "The long or imperial hundredweight (abbreviation cwt) is a unit of mass equal to 112 pounds in US and Canada.", + "XmlDocSummary": "The long or imperial hundredweight (abbreviation cwt) is a unit of mass equal to 112 pounds in US and Canada.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Hundredweight", "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cwt"] + "Abbreviations": [ "cwt" ] } ] }, @@ -211,13 +202,12 @@ }, "FromUnitToBaseFunc": "x/15432.358352941431", "FromBaseToUnitFunc": "x*15432.358352941431", - "XmlDocSummary": - "A grain is a unit of measurement of mass, and in the troy weight, avoirdupois, and Apothecaries' system, equal to exactly 64.79891 milligrams.", + "XmlDocSummary": "A grain is a unit of measurement of mass, and in the troy weight, avoirdupois, and Apothecaries' system, equal to exactly 64.79891 milligrams.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Grain_(unit)", "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gr"] + "Abbreviations": [ "gr" ] } ] }, @@ -234,7 +224,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["M⊙"] + "Abbreviations": [ "M⊙" ] } ] }, @@ -251,9 +241,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["em"] + "Abbreviations": [ "em" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/MassConcentration.json b/Common/UnitDefinitions/MassConcentration.json index 53ad08e0df..8aabae64fb 100644 --- a/Common/UnitDefinitions/MassConcentration.json +++ b/Common/UnitDefinitions/MassConcentration.json @@ -1,8 +1,7 @@ { "Name": "MassConcentration", "BaseUnit": "KilogramPerCubicMeter", - "XmlDoc": - "In chemistry, the mass concentration ρi (or γi) is defined as the mass of a constituent mi divided by the volume of the mixture V", + "XmlDoc": "In chemistry, the mass concentration ρi (or γi) is defined as the mass of a constituent mi divided by the volume of the mixture V", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Mass_concentration_(chemistry)", "BaseDimensions": { "M": 1, @@ -18,11 +17,11 @@ }, "FromUnitToBaseFunc": "x/1e-6", "FromBaseToUnitFunc": "x*1e-6", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/mm³"] + "Abbreviations": [ "g/mm³" ] } ] }, @@ -35,11 +34,11 @@ }, "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/cm³"] + "Abbreviations": [ "g/cm³" ] } ] }, @@ -52,15 +51,15 @@ }, "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": ["Kilo", "Milli", "Micro"], + "Prefixes": [ "Kilo", "Milli", "Micro" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/m³"] + "Abbreviations": [ "g/m³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["г/м³"] + "Abbreviations": [ "г/м³" ] } ] }, @@ -73,11 +72,11 @@ }, "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/mL"] + "Abbreviations": [ "g/mL" ] } ] }, @@ -86,11 +85,11 @@ "PluralName": "GramsPerDeciliter", "FromUnitToBaseFunc": "x/1e-1", "FromBaseToUnitFunc": "x*1e-1", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/dL"] + "Abbreviations": [ "g/dL" ] } ] }, @@ -103,11 +102,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/L"] + "Abbreviations": [ "g/L"] } ] }, @@ -123,7 +122,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t/mm³"] + "Abbreviations": [ "t/mm³" ] } ] }, @@ -139,7 +138,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t/cm³"] + "Abbreviations": [ "t/cm³" ] } ] }, @@ -155,7 +154,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t/m³"] + "Abbreviations": [ "t/m³" ] } ] }, @@ -168,11 +167,11 @@ }, "FromUnitToBaseFunc": "x/3.6127298147753e-5", "FromBaseToUnitFunc": "x*3.6127298147753e-5", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/in³"], + "Abbreviations": [ "lb/in³" ], "AbbreviationsForPrefixes": { "Kilo": "kip/in³" } } ] @@ -186,11 +185,11 @@ }, "FromUnitToBaseFunc": "x/0.062427961", "FromBaseToUnitFunc": "x*0.062427961", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/ft³"], + "Abbreviations": [ "lb/ft³" ], "AbbreviationsForPrefixes": { "Kilo": "kip/ft³" } } ] @@ -207,7 +206,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["slug/ft³"] + "Abbreviations": [ "slug/ft³" ] } ] }, @@ -219,7 +218,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppg (U.S.)"] + "Abbreviations": [ "ppg (U.S.)" ] } ] }, @@ -231,9 +230,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppg (imp.)"] + "Abbreviations": [ "ppg (imp.)" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/MassFlow.json b/Common/UnitDefinitions/MassFlow.json index d5ea22477a..fd012d7c5e 100644 --- a/Common/UnitDefinitions/MassFlow.json +++ b/Common/UnitDefinitions/MassFlow.json @@ -1,8 +1,7 @@ { "Name": "MassFlow", "BaseUnit": "GramPerSecond", - "XmlDoc": - "Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time).", + "XmlDoc": "Mass flow is the ratio of the mass change to the time during which the change occurred (value of mass changes per unit time).", "BaseDimensions": { "M": 1, "T": -1 @@ -13,11 +12,11 @@ "PluralName": "GramsPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/s", "g/S"] + "Abbreviations": [ "g/s", "g/S" ] } ] }, @@ -26,11 +25,11 @@ "PluralName": "GramsPerDay", "FromUnitToBaseFunc": "x/86400", "FromBaseToUnitFunc": "x*86400", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo", "Mega"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/d"] + "Abbreviations": [ "g/d" ] } ] }, @@ -42,7 +41,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/h"] + "Abbreviations": [ "g/h" ] } ] }, @@ -54,11 +53,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kg/h"] + "Abbreviations": [ "kg/h" ] }, { "Culture": "ru-RU", - "Abbreviations": ["кг/ч"] + "Abbreviations": [ "кг/ч" ] } ] }, @@ -70,11 +69,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kg/min"] + "Abbreviations": [ "kg/min" ] }, { "Culture": "ru-RU", - "Abbreviations": ["кг/мин"] + "Abbreviations": [ "кг/мин" ] } ] }, @@ -86,7 +85,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t/h"] + "Abbreviations": [ "t/h" ] } ] }, @@ -95,11 +94,11 @@ "PluralName": "PoundsPerDay", "FromUnitToBaseFunc": "x/190.47936", "FromBaseToUnitFunc": "x*190.47936", - "Prefixes": ["Mega"], + "Prefixes": [ "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/d"] + "Abbreviations": [ "lb/d" ] } ] }, @@ -108,11 +107,11 @@ "PluralName": "PoundsPerHour", "FromUnitToBaseFunc": "x/7.93664", "FromBaseToUnitFunc": "x*7.93664", - "Prefixes": ["Mega"], + "Prefixes": [ "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/h"] + "Abbreviations": [ "lb/h" ] } ] }, @@ -121,11 +120,11 @@ "PluralName": "PoundsPerMinute", "FromUnitToBaseFunc": "x/0.132277", "FromBaseToUnitFunc": "x*0.132277", - "Prefixes": ["Mega"], + "Prefixes": [ "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/min"] + "Abbreviations": [ "lb/min" ] } ] }, @@ -134,11 +133,11 @@ "PluralName": "PoundsPerSecond", "FromUnitToBaseFunc": "x * 453.59237", "FromBaseToUnitFunc": "x / 453.59237", - "Prefixes": ["Mega"], + "Prefixes": [ "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/s"] + "Abbreviations": [ "lb/s" ] } ] }, @@ -150,7 +149,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t/d"] + "Abbreviations": [ "t/d" ] } ] }, @@ -162,9 +161,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["short tn/h"] + "Abbreviations": [ "short tn/h" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/MassFlux.json b/Common/UnitDefinitions/MassFlux.json index 2f20c47d14..40799b9f38 100644 --- a/Common/UnitDefinitions/MassFlux.json +++ b/Common/UnitDefinitions/MassFlux.json @@ -13,11 +13,11 @@ "PluralName": "GramsPerSecondPerSquareMeter", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g·s⁻¹·m⁻²"] + "Abbreviations": [ "g·s⁻¹·m⁻²" ] } ] } diff --git a/Common/UnitDefinitions/MassFraction.json b/Common/UnitDefinitions/MassFraction.json index a4da8bca3f..fdfc016073 100644 --- a/Common/UnitDefinitions/MassFraction.json +++ b/Common/UnitDefinitions/MassFraction.json @@ -4,7 +4,7 @@ "XmlDoc": "The mass fraction is defined as the mass of a constituent divided by the total mass of the mixture.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Mass_fraction_(chemistry)", "Units": [ - { + { "SingularName": "DecimalFraction", "PluralName": "DecimalFractions", "FromUnitToBaseFunc": "x", @@ -12,7 +12,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [""] + "Abbreviations": [ "" ] } ] }, @@ -21,11 +21,11 @@ "PluralName": "GramsPerGram", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/g"] + "Abbreviations": [ "g/g" ] } ] }, @@ -34,11 +34,11 @@ "PluralName": "GramsPerKilogram", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/kg"] + "Abbreviations": [ "g/kg" ] } ] }, @@ -50,7 +50,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["%", "% (w/w)"] + "Abbreviations": [ "%", "% (w/w)" ] } ] }, @@ -62,7 +62,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["‰"] + "Abbreviations": [ "‰" ] } ] }, @@ -74,7 +74,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppm"] + "Abbreviations": [ "ppm" ] } ] }, @@ -86,7 +86,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppb"] + "Abbreviations": [ "ppb" ] } ] }, @@ -98,7 +98,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppt"] + "Abbreviations": [ "ppt" ] } ] } diff --git a/Common/UnitDefinitions/MassMomentOfInertia.json b/Common/UnitDefinitions/MassMomentOfInertia.json index 3a80fd1207..da5357ddf6 100644 --- a/Common/UnitDefinitions/MassMomentOfInertia.json +++ b/Common/UnitDefinitions/MassMomentOfInertia.json @@ -12,11 +12,11 @@ "PluralName": "GramSquareMeters", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": ["Milli", "Kilo"], + "Prefixes": [ "Milli", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g·m²"] + "Abbreviations": [ "g·m²" ] } ] }, @@ -25,11 +25,11 @@ "PluralName": "GramSquareDecimeters", "FromUnitToBaseFunc": "x/1e5", "FromBaseToUnitFunc": "x*1e5", - "Prefixes": ["Milli", "Kilo"], + "Prefixes": [ "Milli", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g·dm²"] + "Abbreviations": [ "g·dm²" ] } ] }, @@ -38,11 +38,11 @@ "PluralName": "GramSquareCentimeters", "FromUnitToBaseFunc": "x/1e7", "FromBaseToUnitFunc": "x*1e7", - "Prefixes": ["Milli", "Kilo"], + "Prefixes": [ "Milli", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g·cm²"] + "Abbreviations": [ "g·cm²" ] } ] }, @@ -51,11 +51,11 @@ "PluralName": "GramSquareMillimeters", "FromUnitToBaseFunc": "x/1e9", "FromBaseToUnitFunc": "x*1e9", - "Prefixes": ["Milli", "Kilo"], + "Prefixes": [ "Milli", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g·mm²"] + "Abbreviations": [ "g·mm²" ] } ] }, @@ -64,11 +64,11 @@ "PluralName": "TonneSquareMeters", "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t·m²"] + "Abbreviations": [ "t·m²" ] } ] }, @@ -77,11 +77,11 @@ "PluralName": "TonneSquareDecimeters", "FromUnitToBaseFunc": "x/1e-1", "FromBaseToUnitFunc": "x*1e-1", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t·dm²"] + "Abbreviations": [ "t·dm²" ] } ] }, @@ -90,11 +90,11 @@ "PluralName": "TonneSquareCentimeters", "FromUnitToBaseFunc": "x/1e1", "FromBaseToUnitFunc": "x*1e1", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t·cm²"] + "Abbreviations": [ "t·cm²" ] } ] }, @@ -103,11 +103,11 @@ "PluralName": "TonneSquareMilimeters", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["t·mm²"] + "Abbreviations": [ "t·mm²" ] } ] }, @@ -119,7 +119,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb·ft²"] + "Abbreviations": [ "lb·ft²" ] } ] }, @@ -131,7 +131,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb·in²"] + "Abbreviations": [ "lb·in²" ] } ] }, @@ -143,7 +143,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["slug·ft²"] + "Abbreviations": [ "slug·ft²" ] } ] }, @@ -155,7 +155,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["slug·in²"] + "Abbreviations": [ "slug·in²" ] } ] } diff --git a/Common/UnitDefinitions/MolarEnergy.json b/Common/UnitDefinitions/MolarEnergy.json index c7cd878358..ad95f79847 100644 --- a/Common/UnitDefinitions/MolarEnergy.json +++ b/Common/UnitDefinitions/MolarEnergy.json @@ -14,13 +14,13 @@ "PluralName": "JoulesPerMole", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/mol"] + "Abbreviations": [ "J/mol" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/MolarEntropy.json b/Common/UnitDefinitions/MolarEntropy.json index 62685231cc..d7bceaf21d 100644 --- a/Common/UnitDefinitions/MolarEntropy.json +++ b/Common/UnitDefinitions/MolarEntropy.json @@ -15,13 +15,13 @@ "PluralName": "JoulesPerMoleKelvin", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/(mol*K)"] + "Abbreviations": [ "J/(mol*K)" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/MolarMass.json b/Common/UnitDefinitions/MolarMass.json index 94fd79c2a3..1d9e82c49c 100644 --- a/Common/UnitDefinitions/MolarMass.json +++ b/Common/UnitDefinitions/MolarMass.json @@ -1,8 +1,7 @@ { "Name": "MolarMass", "BaseUnit": "KilogramPerMole", - "XmlDoc": - "In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance.", + "XmlDoc": "In chemistry, the molar mass M is a physical property defined as the mass of a given substance (chemical element or chemical compound) divided by the amount of substance.", "BaseDimensions": { "M": 1, "N": -1 @@ -13,15 +12,15 @@ "PluralName": "GramsPerMole", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["g/mol"] + "Abbreviations": [ "g/mol" ] }, { "Culture": "ru-RU", - "Abbreviations": ["г/моль"] + "Abbreviations": [ "г/моль" ] } ] }, @@ -30,17 +29,17 @@ "PluralName": "PoundsPerMole", "FromUnitToBaseFunc": "x*0.45359237", "FromBaseToUnitFunc": "x/0.45359237", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/mol"] + "Abbreviations": [ "lb/mol" ] }, { "Culture": "ru-RU", - "Abbreviations": ["фунт/моль"] + "Abbreviations": [ "фунт/моль" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/Molarity.json b/Common/UnitDefinitions/Molarity.json index 0a78e12494..30a55110e0 100644 --- a/Common/UnitDefinitions/Molarity.json +++ b/Common/UnitDefinitions/Molarity.json @@ -1,8 +1,7 @@ { "Name": "Molarity", "BaseUnit": "MolesPerCubicMeter", - "XmlDoc": - "Molar concentration, also called molarity, amount concentration or substance concentration, is a measure of the concentration of a solute in a solution, or of any chemical species, in terms of amount of substance in a given volume. ", + "XmlDoc": "Molar concentration, also called molarity, amount concentration or substance concentration, is a measure of the concentration of a solute in a solution, or of any chemical species, in terms of amount of substance in a given volume. ", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Molar_concentration", "BaseDimensions": { "L": -3, @@ -22,7 +21,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mol/m³"] + "Abbreviations": [ "mol/m³" ] } ] }, @@ -35,13 +34,13 @@ }, "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mol/L", "M"] + "Abbreviations": [ "mol/L", "M"] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/Permeability.json b/Common/UnitDefinitions/Permeability.json index 829d8baec0..8f020ec80f 100644 --- a/Common/UnitDefinitions/Permeability.json +++ b/Common/UnitDefinitions/Permeability.json @@ -1,8 +1,7 @@ { "Name": "Permeability", "BaseUnit": "HenryPerMeter", - "XmlDoc": - "In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself.", + "XmlDoc": "In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Permeability_(electromagnetism)", "BaseDimensions": { "L": 1, @@ -19,7 +18,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["H/m"] + "Abbreviations": [ "H/m" ] } ] } diff --git a/Common/UnitDefinitions/Permittivity.json b/Common/UnitDefinitions/Permittivity.json index fda4c32d63..9ca8109e42 100644 --- a/Common/UnitDefinitions/Permittivity.json +++ b/Common/UnitDefinitions/Permittivity.json @@ -1,8 +1,7 @@ { "Name": "Permittivity", "BaseUnit": "FaradPerMeter", - "XmlDoc": - "In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium.", + "XmlDoc": "In electromagnetism, permittivity is the measure of resistance that is encountered when forming an electric field in a particular medium.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Permittivity", "BaseDimensions": { "L": -3, @@ -19,7 +18,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["F/m"] + "Abbreviations": [ "F/m" ] } ] } diff --git a/Common/UnitDefinitions/Power.json b/Common/UnitDefinitions/Power.json index 73d27233aa..1ac546dbf1 100644 --- a/Common/UnitDefinitions/Power.json +++ b/Common/UnitDefinitions/Power.json @@ -2,8 +2,7 @@ "Name": "Power", "BaseUnit": "Watt", "BaseType": "decimal", - "XmlDoc": - "In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time.", + "XmlDoc": "In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time.", "BaseDimensions": { "L": 2, "M": 1, @@ -15,11 +14,11 @@ "PluralName": "Watts", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Femto", "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera", "Peta"], + "Prefixes": [ "Femto", "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera", "Peta" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W"] + "Abbreviations": [ "W" ] } ] }, @@ -31,7 +30,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["hp(I)"] + "Abbreviations": [ "hp(I)" ] } ] }, @@ -43,7 +42,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["hp(M)"] + "Abbreviations": [ "hp(M)" ] } ] }, @@ -55,7 +54,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["hp(E)"] + "Abbreviations": [ "hp(E)" ] } ] }, @@ -67,7 +66,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["hp(S)"] + "Abbreviations": [ "hp(S)" ] } ] }, @@ -79,7 +78,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["hp(H)"] + "Abbreviations": [ "hp(H)" ] } ] }, @@ -88,11 +87,11 @@ "PluralName": "BritishThermalUnitsPerHour", "FromUnitToBaseFunc": "x*0.293071m", "FromBaseToUnitFunc": "x/0.293071m", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Btu/h", "Btu/hr"] + "Abbreviations": [ "Btu/h", "Btu/hr" ] } ] }, @@ -101,11 +100,11 @@ "PluralName": "JoulesPerHour", "FromUnitToBaseFunc": "x/3600m", "FromBaseToUnitFunc": "x*3600m", - "Prefixes": ["Milli", "Kilo", "Mega", "Giga"], + "Prefixes": [ "Milli", "Kilo", "Mega", "Giga" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/h"] + "Abbreviations": [ "J/h" ] } ] }, diff --git a/Common/UnitDefinitions/PowerDensity.json b/Common/UnitDefinitions/PowerDensity.json index 93f4ae4866..137b03aa1e 100644 --- a/Common/UnitDefinitions/PowerDensity.json +++ b/Common/UnitDefinitions/PowerDensity.json @@ -18,11 +18,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/m³"] + "Abbreviations": [ "W/m³" ] } ] }, @@ -31,11 +31,11 @@ "PluralName": "WattsPerCubicInch", "FromUnitToBaseFunc": "x*6.102374409473228e4", "FromBaseToUnitFunc": "x/6.102374409473228e4", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/in³"] + "Abbreviations": [ "W/in³" ] } ] }, @@ -44,11 +44,11 @@ "PluralName": "WattsPerCubicFoot", "FromUnitToBaseFunc": "x*3.531466672148859e1", "FromBaseToUnitFunc": "x/3.531466672148859e1", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/ft³"] + "Abbreviations": [ "W/ft³" ] } ] }, @@ -57,11 +57,11 @@ "PluralName": "WattsPerLiter", "FromUnitToBaseFunc": "x*1.0e3", "FromBaseToUnitFunc": "x/1.0e3", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Deci", "Deca", "Kilo", "Mega", "Giga", "Tera" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/l"] + "Abbreviations": [ "W/l" ] } ] } diff --git a/Common/UnitDefinitions/PowerRatio.json b/Common/UnitDefinitions/PowerRatio.json index 68722aeb76..1a0bf26e9f 100644 --- a/Common/UnitDefinitions/PowerRatio.json +++ b/Common/UnitDefinitions/PowerRatio.json @@ -13,7 +13,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dBW"] + "Abbreviations": [ "dBW" ] } ] }, @@ -25,7 +25,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dBmW", "dBm"] + "Abbreviations": [ "dBmW", "dBm" ] } ] } diff --git a/Common/UnitDefinitions/Pressure.json b/Common/UnitDefinitions/Pressure.json index 2369eca3d0..a58487f142 100644 --- a/Common/UnitDefinitions/Pressure.json +++ b/Common/UnitDefinitions/Pressure.json @@ -1,8 +1,7 @@ { "Name": "Pressure", "BaseUnit": "Pascal", - "XmlDoc": - "Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa).", + "XmlDoc": "Pressure (symbol: P or p) is the ratio of force to the area over which that force is distributed. Pressure is force per unit area applied in a direction perpendicular to the surface of an object. Gauge pressure (also spelled gage pressure)[a] is the pressure relative to the local atmospheric or ambient pressure. Pressure is measured in any unit of force divided by any unit of area. The SI unit of pressure is the newton per square metre, which is called the pascal (Pa) after the seventeenth-century philosopher and scientist Blaise Pascal. A pressure of 1 Pa is small; it approximately equals the pressure exerted by a dollar bill resting flat on a table. Everyday pressures are often stated in kilopascals (1 kPa = 1000 Pa).", "BaseDimensions": { "L": -1, "M": 1, @@ -19,15 +18,15 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Micro", "Milli", "Deca", "Hecto", "Kilo", "Mega", "Giga"], + "Prefixes": [ "Micro", "Milli", "Deca", "Hecto", "Kilo", "Mega", "Giga" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Pa"] + "Abbreviations": [ "Pa" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Па"] + "Abbreviations": [ "Па" ] } ] }, @@ -39,11 +38,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["atm"] + "Abbreviations": [ "atm" ] }, { "Culture": "ru-RU", - "Abbreviations": ["атм"] + "Abbreviations": [ "атм" ] } ] }, @@ -52,15 +51,15 @@ "PluralName": "Bars", "FromUnitToBaseFunc": "x*1e5", "FromBaseToUnitFunc": "x/1e5", - "Prefixes": ["Micro", "Milli", "Centi", "Deci", "Kilo", "Mega"], + "Prefixes": [ "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bar"] + "Abbreviations": [ "bar" ] }, { "Culture": "ru-RU", - "Abbreviations": ["бар"] + "Abbreviations": [ "бар" ] } ] }, @@ -72,11 +71,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf/m²"] + "Abbreviations": [ "kgf/m²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["кгс/м²"] + "Abbreviations": [ "кгс/м²" ] } ] }, @@ -88,11 +87,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf/cm²"] + "Abbreviations": [ "kgf/cm²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["кгс/см²"] + "Abbreviations": [ "кгс/см²" ] } ] }, @@ -104,11 +103,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf/mm²"] + "Abbreviations": [ "kgf/mm²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["кгс/мм²"] + "Abbreviations": [ "кгс/мм²" ] } ] }, @@ -117,15 +116,15 @@ "PluralName": "NewtonsPerSquareMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N/m²"] + "Abbreviations": [ "N/m²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Н/м²"] + "Abbreviations": [ "Н/м²" ] } ] }, @@ -134,15 +133,15 @@ "PluralName": "NewtonsPerSquareCentimeter", "FromUnitToBaseFunc": "x*1e4", "FromBaseToUnitFunc": "x/1e4", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N/cm²"] + "Abbreviations": [ "N/cm²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Н/см²"] + "Abbreviations": [ "Н/см²" ] } ] }, @@ -151,15 +150,15 @@ "PluralName": "NewtonsPerSquareMillimeter", "FromUnitToBaseFunc": "x*1e6", "FromBaseToUnitFunc": "x/1e6", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N/mm²"] + "Abbreviations": [ "N/mm²" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Н/мм²"] + "Abbreviations": [ "Н/мм²" ] } ] }, @@ -171,11 +170,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["at"] + "Abbreviations": [ "at" ] }, { "Culture": "ru-RU", - "Abbreviations": ["ат"] + "Abbreviations": [ "ат" ] } ] }, @@ -187,11 +186,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["torr"] + "Abbreviations": [ "torr" ] }, { "Culture": "ru-RU", - "Abbreviations": ["торр"] + "Abbreviations": [ "торр" ] } ] }, @@ -200,11 +199,11 @@ "PluralName": "PoundsForcePerSquareInch", "FromUnitToBaseFunc": "x*6.894757293168361e3", "FromBaseToUnitFunc": "x/6.894757293168361e3", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["psi", "lb/in²"], + "Abbreviations": [ "psi", "lb/in²" ], "AbbreviationsForPrefixes": { "Kilo": "kipf/in²" } } ] @@ -214,11 +213,11 @@ "PluralName": "PoundsForcePerSquareFoot", "FromUnitToBaseFunc": "x*4.788025898033584e1", "FromBaseToUnitFunc": "x/4.788025898033584e1", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lb/ft²"], + "Abbreviations": [ "lb/ft²" ], "AbbreviationsForPrefixes": { "Kilo": "kipf/ft²" } } ] @@ -231,7 +230,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf/mm²"] + "Abbreviations": [ "tf/mm²" ] } ] }, @@ -243,7 +242,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf/m²"] + "Abbreviations": [ "tf/m²" ] } ] }, @@ -255,7 +254,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m of head"] + "Abbreviations": [ "m of head" ] } ] }, @@ -267,7 +266,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf/cm²"] + "Abbreviations": [ "tf/cm²" ] } ] }, @@ -279,7 +278,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft of head"] + "Abbreviations": [ "ft of head" ] } ] }, @@ -291,7 +290,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mmHg"] + "Abbreviations": [ "mmHg" ] } ] }, @@ -303,7 +302,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["inHg"] + "Abbreviations": [ "inHg" ] } ] }, @@ -315,7 +314,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dyn/cm²"] + "Abbreviations": [ "dyn/cm²" ] } ] }, @@ -327,7 +326,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbm/(in·s²)", "lb/(in·s²)"] + "Abbreviations": [ "lbm/(in·s²)", "lb/(in·s²)" ] } ] }, @@ -339,9 +338,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["wc"] + "Abbreviations": [ "wc" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/PressureChangeRate.json b/Common/UnitDefinitions/PressureChangeRate.json index 8cc9066f17..14d7f017bc 100644 --- a/Common/UnitDefinitions/PressureChangeRate.json +++ b/Common/UnitDefinitions/PressureChangeRate.json @@ -1,8 +1,7 @@ { "Name": "PressureChangeRate", "BaseUnit": "PascalPerSecond", - "XmlDoc": - "Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time).", + "XmlDoc": "Pressure change rate is the ratio of the pressure change to the time during which the change occurred (value of pressure changes per unit time).", "BaseDimensions": { "L": -1, "M": 1, @@ -14,15 +13,15 @@ "PluralName": "PascalsPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Pa/s"] + "Abbreviations": [ "Pa/s" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Па/с"] + "Abbreviations": [ "Па/с" ] } ] }, @@ -31,15 +30,15 @@ "PluralName": "PascalsPerMinute", "FromUnitToBaseFunc": "x/60", "FromBaseToUnitFunc": "x*60", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Pa/min"] + "Abbreviations": [ "Pa/min" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Па/с"] + "Abbreviations": [ "Па/с" ] } ] }, @@ -51,13 +50,13 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["atm/s"] + "Abbreviations": [ "atm/s" ] }, { "Culture": "ru-RU", - "Abbreviations": ["атм/с"] + "Abbreviations": [ "атм/с" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/Ratio.json b/Common/UnitDefinitions/Ratio.json index d2ff8e955b..c9387a5397 100644 --- a/Common/UnitDefinitions/Ratio.json +++ b/Common/UnitDefinitions/Ratio.json @@ -1,8 +1,7 @@ { "Name": "Ratio", "BaseUnit": "DecimalFraction", - "XmlDoc": - "In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as \"a to b\" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer).", + "XmlDoc": "In mathematics, a ratio is a relationship between two numbers of the same kind (e.g., objects, persons, students, spoonfuls, units of whatever identical dimension), usually expressed as \"a to b\" or a:b, sometimes expressed arithmetically as a dimensionless quotient of the two that explicitly indicates how many times the first number contains the second (not necessarily an integer).", "Units": [ { "SingularName": "DecimalFraction", @@ -12,7 +11,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [""] + "Abbreviations": [ "" ] } ] }, @@ -24,7 +23,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["%"] + "Abbreviations": [ "%" ] } ] }, @@ -36,7 +35,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["‰"] + "Abbreviations": [ "‰" ] } ] }, @@ -48,7 +47,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppm"] + "Abbreviations": [ "ppm" ] } ] }, @@ -60,7 +59,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppb"] + "Abbreviations": [ "ppb" ] } ] }, @@ -72,7 +71,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppt"] + "Abbreviations": [ "ppt" ] } ] } diff --git a/Common/UnitDefinitions/RatioChangeRate.json b/Common/UnitDefinitions/RatioChangeRate.json index 554ac130d1..019bd89419 100644 --- a/Common/UnitDefinitions/RatioChangeRate.json +++ b/Common/UnitDefinitions/RatioChangeRate.json @@ -11,7 +11,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["%/s"] + "Abbreviations": [ "%/s" ] } ] }, @@ -23,9 +23,10 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["/s"] + "Abbreviations": [ "/s" ] } ] } + ] } \ No newline at end of file diff --git a/Common/UnitDefinitions/ReactiveEnergy.json b/Common/UnitDefinitions/ReactiveEnergy.json index f10dd51b34..9ac64f67d4 100644 --- a/Common/UnitDefinitions/ReactiveEnergy.json +++ b/Common/UnitDefinitions/ReactiveEnergy.json @@ -1,8 +1,7 @@ { "Name": "ReactiveEnergy", "BaseUnit": "VoltampereReactiveHour", - "XmlDoc": - "The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour.", + "XmlDoc": "The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour.", "BaseDimensions": { "L": 2, "M": 1, @@ -14,11 +13,11 @@ "PluralName": "VoltampereReactiveHours", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["varh"] + "Abbreviations": [ "varh" ] } ] } diff --git a/Common/UnitDefinitions/ReactivePower.json b/Common/UnitDefinitions/ReactivePower.json index 390530c770..e02d22fe96 100644 --- a/Common/UnitDefinitions/ReactivePower.json +++ b/Common/UnitDefinitions/ReactivePower.json @@ -1,8 +1,7 @@ { "Name": "ReactivePower", "BaseUnit": "VoltampereReactive", - "XmlDoc": - "Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase.", + "XmlDoc": "Volt-ampere reactive (var) is a unit by which reactive power is expressed in an AC electric power system. Reactive power exists in an AC circuit when the current and voltage are not in phase.", "BaseDimensions": { "L": 2, "M": 1, @@ -14,11 +13,11 @@ "PluralName": "VoltamperesReactive", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega", "Giga"], + "Prefixes": [ "Kilo", "Mega", "Giga" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["var"] + "Abbreviations": [ "var" ] } ] } diff --git a/Common/UnitDefinitions/RotationalAcceleration.json b/Common/UnitDefinitions/RotationalAcceleration.json index 8132039484..78d28c1622 100644 --- a/Common/UnitDefinitions/RotationalAcceleration.json +++ b/Common/UnitDefinitions/RotationalAcceleration.json @@ -14,7 +14,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["rad/s²"] + "Abbreviations": [ "rad/s²" ] } ] }, @@ -26,7 +26,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°/s²", "deg/s²"] + "Abbreviations": [ "°/s²", "deg/s²" ] } ] }, @@ -38,7 +38,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["rpm/s"] + "Abbreviations": [ "rpm/s" ] } ] }, @@ -50,7 +50,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["r/s²"] + "Abbreviations": [ "r/s²" ] } ] } diff --git a/Common/UnitDefinitions/RotationalSpeed.json b/Common/UnitDefinitions/RotationalSpeed.json index 2d33d11290..66c5bd8195 100644 --- a/Common/UnitDefinitions/RotationalSpeed.json +++ b/Common/UnitDefinitions/RotationalSpeed.json @@ -1,8 +1,7 @@ { "Name": "RotationalSpeed", "BaseUnit": "RadianPerSecond", - "XmlDoc": - "Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter \"omega\").", + "XmlDoc": "Rotational speed (sometimes called speed of revolution) is the number of complete rotations, revolutions, cycles, or turns per time unit. Rotational speed is a cyclic frequency, measured in radians per second or in hertz in the SI System by scientists, or in revolutions per minute (rpm or min-1) or revolutions per second in everyday life. The symbol for rotational speed is ω (the Greek lowercase letter \"omega\").", "BaseDimensions": { "T": -1 }, @@ -12,15 +11,15 @@ "PluralName": "RadiansPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["rad/s"] + "Abbreviations": [ "rad/s" ] }, { "Culture": "ru-RU", - "Abbreviations": ["рад/с"] + "Abbreviations": [ "рад/с" ] } ] }, @@ -29,15 +28,15 @@ "PluralName": "DegreesPerSecond", "FromUnitToBaseFunc": "(Math.PI/180)*x", "FromBaseToUnitFunc": "(180/Math.PI)*x", - "Prefixes": ["Nano", "Micro", "Milli"], + "Prefixes": [ "Nano", "Micro", "Milli" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°/s", "deg/s"] + "Abbreviations": [ "°/s", "deg/s" ] }, { "Culture": "ru-RU", - "Abbreviations": ["°/с"] + "Abbreviations": [ "°/с" ] } ] }, @@ -49,7 +48,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°/min", "deg/min"] + "Abbreviations": [ "°/min", "deg/min" ] } ] }, @@ -61,11 +60,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["r/s"] + "Abbreviations": [ "r/s" ] }, { "Culture": "ru-RU", - "Abbreviations": ["об/с"] + "Abbreviations": [ "об/с" ] } ] }, @@ -77,11 +76,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["rpm", "r/min"] + "Abbreviations": [ "rpm", "r/min" ] }, { "Culture": "ru-RU", - "Abbreviations": ["об/мин"] + "Abbreviations": [ "об/мин" ] } ] } diff --git a/Common/UnitDefinitions/RotationalStiffness.json b/Common/UnitDefinitions/RotationalStiffness.json index e997cb1139..59b9afd6fa 100644 --- a/Common/UnitDefinitions/RotationalStiffness.json +++ b/Common/UnitDefinitions/RotationalStiffness.json @@ -13,11 +13,11 @@ "PluralName": "NewtonMetersPerRadian", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N·m/rad", "Nm/rad"] + "Abbreviations": [ "N·m/rad", "Nm/rad" ] } ] } diff --git a/Common/UnitDefinitions/RotationalStiffnessPerLength.json b/Common/UnitDefinitions/RotationalStiffnessPerLength.json index ec46b3dafb..2135137175 100644 --- a/Common/UnitDefinitions/RotationalStiffnessPerLength.json +++ b/Common/UnitDefinitions/RotationalStiffnessPerLength.json @@ -13,11 +13,11 @@ "PluralName": "NewtonMetersPerRadianPerMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N·m/rad/m", "Nm/rad/m"] + "Abbreviations": [ "N·m/rad/m", "Nm/rad/m" ] } ] } diff --git a/Common/UnitDefinitions/SolidAngle.json b/Common/UnitDefinitions/SolidAngle.json index ecc6f245bf..10cced6eee 100644 --- a/Common/UnitDefinitions/SolidAngle.json +++ b/Common/UnitDefinitions/SolidAngle.json @@ -1,8 +1,7 @@ { "Name": "SolidAngle", "BaseUnit": "Steradian", - "XmlDoc": - "In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point.", + "XmlDoc": "In geometry, a solid angle is the two-dimensional angle in three-dimensional space that an object subtends at a point.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Solid_angle", "Units": [ { @@ -13,7 +12,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["sr"] + "Abbreviations": [ "sr" ] } ] } diff --git a/Common/UnitDefinitions/SpecificEnergy.json b/Common/UnitDefinitions/SpecificEnergy.json index 030864f872..8c706f0b83 100644 --- a/Common/UnitDefinitions/SpecificEnergy.json +++ b/Common/UnitDefinitions/SpecificEnergy.json @@ -13,11 +13,11 @@ "PluralName": "JoulesPerKilogram", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/kg"] + "Abbreviations": [ "J/kg" ] } ] }, @@ -26,11 +26,11 @@ "PluralName": "CaloriesPerGram", "FromUnitToBaseFunc": "x*4.184e3", "FromBaseToUnitFunc": "x/4.184e3", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cal/g"] + "Abbreviations": [ "cal/g" ] } ] }, @@ -39,11 +39,11 @@ "PluralName": "WattHoursPerKilogram", "FromUnitToBaseFunc": "x*3.6e3", "FromBaseToUnitFunc": "x/3.6e3", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Wh/kg"] + "Abbreviations": [ "Wh/kg" ] } ] }, @@ -55,9 +55,10 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["btu/lb"] + "Abbreviations": [ "btu/lb" ] } ] } + ] } \ No newline at end of file diff --git a/Common/UnitDefinitions/SpecificEntropy.json b/Common/UnitDefinitions/SpecificEntropy.json index 1bdb75379a..4bfeac565a 100644 --- a/Common/UnitDefinitions/SpecificEntropy.json +++ b/Common/UnitDefinitions/SpecificEntropy.json @@ -1,8 +1,7 @@ { "Name": "SpecificEntropy", "BaseUnit": "JoulePerKilogramKelvin", - "XmlDoc": - "Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass.", + "XmlDoc": "Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass.", "BaseDimensions": { "L": 2, "T": -2, @@ -14,11 +13,11 @@ "PluralName": "JoulesPerKilogramKelvin", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/kg.K"] + "Abbreviations": [ "J/kg.K" ] } ] }, @@ -27,11 +26,11 @@ "PluralName": "JoulesPerKilogramDegreeCelsius", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["J/kg.C"] + "Abbreviations": [ "J/kg.C" ] } ] }, @@ -40,11 +39,11 @@ "PluralName": "CaloriesPerGramKelvin", "FromUnitToBaseFunc": "x*4.184e3", "FromBaseToUnitFunc": "x/4.184e3", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cal/g.K"] + "Abbreviations": [ "cal/g.K" ] } ] }, @@ -56,7 +55,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["BTU/lb·°F", "BTU/lbm·°F"] + "Abbreviations": [ "BTU/lb·°F", "BTU/lbm·°F" ] } ] } diff --git a/Common/UnitDefinitions/SpecificVolume.json b/Common/UnitDefinitions/SpecificVolume.json index c977e4dd7b..9a6d3a2083 100644 --- a/Common/UnitDefinitions/SpecificVolume.json +++ b/Common/UnitDefinitions/SpecificVolume.json @@ -1,8 +1,7 @@ { "Name": "SpecificVolume", "BaseUnit": "CubicMeterPerKilogram", - "XmlDoc": - "In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well.", + "XmlDoc": "In thermodynamics, the specific volume of a substance is the ratio of the substance's volume to its mass. It is the reciprocal of density and an intrinsic property of matter as well.", "BaseDimensions": { "L": 3, "M": -1 @@ -13,11 +12,11 @@ "PluralName": "CubicMetersPerKilogram", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Milli"], + "Prefixes": [ "Milli" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m³/kg"] + "Abbreviations": [ "m³/kg" ] } ] }, @@ -30,9 +29,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft³/lb"] + "Abbreviations": [ "ft³/lb" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/SpecificWeight.json b/Common/UnitDefinitions/SpecificWeight.json index 49edec6f7c..5ffecf2923 100644 --- a/Common/UnitDefinitions/SpecificWeight.json +++ b/Common/UnitDefinitions/SpecificWeight.json @@ -1,8 +1,7 @@ { "Name": "SpecificWeight", "BaseUnit": "NewtonPerCubicMeter", - "XmlDoc": - "The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume.", + "XmlDoc": "The SpecificWeight, or more precisely, the volumetric weight density, of a substance is its weight per unit volume.", "XmlDocRemarks": "http://en.wikipedia.org/wiki/Specificweight", "BaseDimensions": { "L": -2, @@ -15,11 +14,11 @@ "PluralName": "NewtonsPerCubicMillimeter", "FromUnitToBaseFunc": "x*1000000000", "FromBaseToUnitFunc": "x*0.000000001", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N/mm³"] + "Abbreviations": [ "N/mm³" ] } ] }, @@ -28,11 +27,11 @@ "PluralName": "NewtonsPerCubicCentimeter", "FromUnitToBaseFunc": "x*1000000", "FromBaseToUnitFunc": "x*0.000001", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N/cm³"] + "Abbreviations": [ "N/cm³" ] } ] }, @@ -41,11 +40,11 @@ "PluralName": "NewtonsPerCubicMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N/m³"] + "Abbreviations": [ "N/m³" ] } ] }, @@ -57,7 +56,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf/mm³"] + "Abbreviations": [ "kgf/mm³" ] } ] }, @@ -69,7 +68,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf/cm³"] + "Abbreviations": [ "kgf/cm³" ] } ] }, @@ -81,7 +80,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf/m³"] + "Abbreviations": [ "kgf/m³" ] } ] }, @@ -90,11 +89,11 @@ "PluralName": "PoundsForcePerCubicInch", "FromUnitToBaseFunc": "x*2.714471375263134e5", "FromBaseToUnitFunc": "x/2.714471375263134e5", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf/in³"], + "Abbreviations": [ "lbf/in³" ], "AbbreviationsForPrefixes": { "Kilo": "kipf/in³" } } ] @@ -104,11 +103,11 @@ "PluralName": "PoundsForcePerCubicFoot", "FromUnitToBaseFunc": "x*1.570874638462462e2", "FromBaseToUnitFunc": "x/1.570874638462462e2", - "Prefixes": ["Kilo"], + "Prefixes": [ "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf/ft³"], + "Abbreviations": [ "lbf/ft³" ], "AbbreviationsForPrefixes": { "Kilo": "kipf/ft³" } } ] @@ -121,7 +120,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf/mm³"] + "Abbreviations": [ "tf/mm³" ] } ] }, @@ -133,7 +132,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf/cm³"] + "Abbreviations": [ "tf/cm³" ] } ] }, @@ -145,9 +144,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf/m³"] + "Abbreviations": [ "tf/m³" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/Speed.json b/Common/UnitDefinitions/Speed.json index 7fd65b7d75..f912c81946 100644 --- a/Common/UnitDefinitions/Speed.json +++ b/Common/UnitDefinitions/Speed.json @@ -1,8 +1,7 @@ { "Name": "Speed", "BaseUnit": "MeterPerSecond", - "XmlDoc": - "In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero.", + "XmlDoc": "In everyday use and in kinematics, the speed of an object is the magnitude of its velocity (the rate of change of its position); it is thus a scalar quantity.[1] The average speed of an object in an interval of time is the distance travelled by the object divided by the duration of the interval;[2] the instantaneous speed is the limit of the average speed as the duration of the time interval approaches zero.", "BaseDimensions": { "L": 1, "T": -1 @@ -17,11 +16,11 @@ }, "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m/s"] + "Abbreviations": [ "m/s" ] } ] }, @@ -34,11 +33,11 @@ }, "FromUnitToBaseFunc": "x/60", "FromBaseToUnitFunc": "x*60", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m/min"] + "Abbreviations": [ "m/min" ] } ] }, @@ -51,11 +50,11 @@ }, "FromUnitToBaseFunc": "x/3600", "FromBaseToUnitFunc": "x*3600", - "Prefixes": ["Milli", "Centi", "Kilo"], + "Prefixes": [ "Milli", "Centi", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m/h"] + "Abbreviations": [ "m/h" ] } ] }, @@ -71,7 +70,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft/s"] + "Abbreviations": [ "ft/s" ] } ] }, @@ -87,7 +86,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft/min"] + "Abbreviations": [ "ft/min" ] } ] }, @@ -103,7 +102,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft/h"] + "Abbreviations": [ "ft/h" ] } ] }, @@ -119,7 +118,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ftUS/s"] + "Abbreviations": [ "ftUS/s" ] } ] }, @@ -135,7 +134,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ftUS/min"] + "Abbreviations": [ "ftUS/min" ] } ] }, @@ -151,7 +150,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ftUS/h"] + "Abbreviations": [ "ftUS/h" ] } ] }, @@ -167,7 +166,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["in/s"] + "Abbreviations": [ "in/s" ] } ] }, @@ -183,7 +182,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["in/min"] + "Abbreviations": [ "in/min" ] } ] }, @@ -199,7 +198,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["in/h"] + "Abbreviations": [ "in/h" ] } ] }, @@ -215,7 +214,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["yd/s"] + "Abbreviations": [ "yd/s" ] } ] }, @@ -231,7 +230,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["yd/min"] + "Abbreviations": [ "yd/min" ] } ] }, @@ -247,7 +246,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["yd/h"] + "Abbreviations": [ "yd/h" ] } ] }, @@ -263,7 +262,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kn", "kt", "knot", "knots"] + "Abbreviations": [ "kn", "kt", "knot", "knots" ] } ] }, @@ -279,7 +278,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mph"] + "Abbreviations": [ "mph" ] } ] } diff --git a/Common/UnitDefinitions/Temperature.json b/Common/UnitDefinitions/Temperature.json index 5c3795609d..15a87bdc4f 100644 --- a/Common/UnitDefinitions/Temperature.json +++ b/Common/UnitDefinitions/Temperature.json @@ -1,8 +1,7 @@ { "Name": "Temperature", "BaseUnit": "Kelvin", - "XmlDoc": - "A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics.", + "XmlDoc": "A temperature is a numerical measure of hot or cold. Its measurement is by detection of heat radiation or particle velocity or kinetic energy, or by the bulk behavior of a thermometric material. It may be calibrated in any of various temperature scales, Celsius, Fahrenheit, Kelvin, etc. The fundamental physical definition of temperature is provided by thermodynamics.", "GenerateArithmetic": false, "BaseDimensions": { "Θ": 1 @@ -19,7 +18,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["K"] + "Abbreviations": [ "K" ] } ] }, @@ -34,7 +33,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°C"] + "Abbreviations": [ "°C" ] } ] }, @@ -49,7 +48,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°De"] + "Abbreviations": [ "°De" ] } ] }, @@ -64,7 +63,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°F"] + "Abbreviations": [ "°F" ] } ] }, @@ -79,7 +78,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°N"] + "Abbreviations": [ "°N" ] } ] }, @@ -94,7 +93,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°R"] + "Abbreviations": [ "°R" ] } ] }, @@ -109,7 +108,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°Ré"] + "Abbreviations": [ "°Ré" ] } ] }, @@ -124,7 +123,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°Rø"] + "Abbreviations": [ "°Rø" ] } ] }, @@ -136,7 +135,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["T⊙"] + "Abbreviations": [ "T⊙" ] } ] } diff --git a/Common/UnitDefinitions/TemperatureChangeRate.json b/Common/UnitDefinitions/TemperatureChangeRate.json index 9bd33a1d9d..4d08f7b5dd 100644 --- a/Common/UnitDefinitions/TemperatureChangeRate.json +++ b/Common/UnitDefinitions/TemperatureChangeRate.json @@ -1,8 +1,7 @@ { "Name": "TemperatureChangeRate", "BaseUnit": "DegreeCelsiusPerSecond", - "XmlDoc": - "Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time).", + "XmlDoc": "Temperature change rate is the ratio of the temperature change to the time during which the change occurred (value of temperature changes per unit time).", "BaseDimensions": { "T": -1, "Θ": 1 @@ -13,11 +12,11 @@ "PluralName": "DegreesCelsiusPerSecond", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Deca", "Hecto", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°C/s"] + "Abbreviations": [ "°C/s" ] } ] }, @@ -29,7 +28,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["°C/min"] + "Abbreviations": [ "°C/min" ] } ] } diff --git a/Common/UnitDefinitions/TemperatureDelta.json b/Common/UnitDefinitions/TemperatureDelta.json index b07dfec64c..34b37da1ea 100644 --- a/Common/UnitDefinitions/TemperatureDelta.json +++ b/Common/UnitDefinitions/TemperatureDelta.json @@ -11,7 +11,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["∆K"] + "Abbreviations": [ "∆K" ] } ] }, @@ -23,7 +23,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["∆°C"] + "Abbreviations": [ "∆°C" ] } ] }, @@ -35,7 +35,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["∆°De"] + "Abbreviations": [ "∆°De" ] } ] }, @@ -47,7 +47,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["∆°F"] + "Abbreviations": [ "∆°F" ] } ] }, @@ -59,7 +59,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["∆°N"] + "Abbreviations": [ "∆°N" ] } ] }, @@ -71,7 +71,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["∆°R"] + "Abbreviations": [ "∆°R" ] } ] }, @@ -83,7 +83,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["∆°Ré"] + "Abbreviations": [ "∆°Ré" ] } ] }, @@ -95,7 +95,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["∆°Rø"] + "Abbreviations": [ "∆°Rø" ] } ] } diff --git a/Common/UnitDefinitions/ThermalConductivity.json b/Common/UnitDefinitions/ThermalConductivity.json index 0aefcee915..67afec23b4 100644 --- a/Common/UnitDefinitions/ThermalConductivity.json +++ b/Common/UnitDefinitions/ThermalConductivity.json @@ -18,7 +18,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["W/m·K"] + "Abbreviations": [ "W/m·K" ] } ] }, @@ -30,7 +30,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["BTU/h·ft·°F"] + "Abbreviations": [ "BTU/h·ft·°F" ] } ] } diff --git a/Common/UnitDefinitions/ThermalResistance.json b/Common/UnitDefinitions/ThermalResistance.json index 21292d4383..c5fc7d8415 100644 --- a/Common/UnitDefinitions/ThermalResistance.json +++ b/Common/UnitDefinitions/ThermalResistance.json @@ -16,7 +16,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m²K/kW"] + "Abbreviations": [ "m²K/kW" ] } ] }, @@ -28,7 +28,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m²°C/W"] + "Abbreviations": [ "m²°C/W" ] } ] }, @@ -40,7 +40,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cm²K/W"] + "Abbreviations": [ "cm²K/W" ] } ] }, @@ -52,7 +52,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cm²Hr°C/kcal"] + "Abbreviations": [ "cm²Hr°C/kcal" ] } ] }, @@ -64,9 +64,10 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["Hrft²°F/Btu"] + "Abbreviations": [ "Hrft²°F/Btu" ] } ] } + ] } \ No newline at end of file diff --git a/Common/UnitDefinitions/Torque.json b/Common/UnitDefinitions/Torque.json index 29a5f1dc94..90e8a26d45 100644 --- a/Common/UnitDefinitions/Torque.json +++ b/Common/UnitDefinitions/Torque.json @@ -1,8 +1,7 @@ { "Name": "Torque", "BaseUnit": "NewtonMeter", - "XmlDoc": - "Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt.", + "XmlDoc": "Torque, moment or moment of force (see the terminology below), is the tendency of a force to rotate an object about an axis,[1] fulcrum, or pivot. Just as a force is a push or a pull, a torque can be thought of as a twist to an object. Mathematically, torque is defined as the cross product of the lever-arm distance and force, which tends to produce rotation. Loosely speaking, torque is a measure of the turning force on an object such as a bolt or a flywheel. For example, pushing or pulling the handle of a wrench connected to a nut or bolt produces a torque (turning force) that loosens or tightens the nut or bolt.", "BaseDimensions": { "L": 2, "M": 1, @@ -14,11 +13,11 @@ "PluralName": "NewtonMillimeters", "FromUnitToBaseFunc": "x*0.001", "FromBaseToUnitFunc": "x*1000", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N·mm"] + "Abbreviations": [ "N·mm" ] } ] }, @@ -27,11 +26,11 @@ "PluralName": "NewtonCentimeters", "FromUnitToBaseFunc": "x*0.01", "FromBaseToUnitFunc": "x*100", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N·cm"] + "Abbreviations": [ "N·cm" ] } ] }, @@ -40,15 +39,15 @@ "PluralName": "NewtonMeters", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N·m"] + "Abbreviations": [ "N·m" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Н·м"] + "Abbreviations": [ "Н·м" ] } ] }, @@ -57,11 +56,11 @@ "PluralName": "PoundForceInches", "FromUnitToBaseFunc": "x*1.129848290276167e-1", "FromBaseToUnitFunc": "x/1.129848290276167e-1", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf·in"], + "Abbreviations": [ "lbf·in" ], "AbbreviationsForPrefixes": { "Kilo": "kipf·in" } } ] @@ -71,11 +70,11 @@ "PluralName": "PoundForceFeet", "FromUnitToBaseFunc": "x*1.3558179483314", "FromBaseToUnitFunc": "x/1.3558179483314", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf·ft"], + "Abbreviations": [ "lbf·ft" ], "AbbreviationsForPrefixes": { "Kilo": "kipf·ft" } } ] @@ -88,7 +87,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf·mm"] + "Abbreviations": [ "kgf·mm" ] } ] }, @@ -100,7 +99,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf·cm"] + "Abbreviations": [ "kgf·cm" ] } ] }, @@ -112,7 +111,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf·m"] + "Abbreviations": [ "kgf·m" ] } ] }, @@ -124,7 +123,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf·mm"] + "Abbreviations": [ "tf·mm" ] } ] }, @@ -136,7 +135,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf·cm"] + "Abbreviations": [ "tf·cm" ] } ] }, @@ -148,9 +147,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf·m"] + "Abbreviations": [ "tf·m" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/TorquePerLength.json b/Common/UnitDefinitions/TorquePerLength.json index 5656117ac0..9356721394 100644 --- a/Common/UnitDefinitions/TorquePerLength.json +++ b/Common/UnitDefinitions/TorquePerLength.json @@ -13,11 +13,11 @@ "PluralName": "NewtonMillimetersPerMeter", "FromUnitToBaseFunc": "x*0.001", "FromBaseToUnitFunc": "x*1000", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N·mm/m"] + "Abbreviations": [ "N·mm/m" ] } ] }, @@ -26,11 +26,11 @@ "PluralName": "NewtonCentimetersPerMeter", "FromUnitToBaseFunc": "x*0.01", "FromBaseToUnitFunc": "x*100", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N·cm/m"] + "Abbreviations": [ "N·cm/m" ] } ] }, @@ -39,15 +39,15 @@ "PluralName": "NewtonMetersPerMeter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["N·m/m"] + "Abbreviations": [ "N·m/m" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Н·м/м"] + "Abbreviations": [ "Н·м/м" ] } ] }, @@ -56,11 +56,11 @@ "PluralName": "PoundForceInchesPerFoot", "FromUnitToBaseFunc": "x*0.370685147638", "FromBaseToUnitFunc": "x/0.370685147638", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf·in/ft"], + "Abbreviations": [ "lbf·in/ft" ], "AbbreviationsForPrefixes": { "Kilo": "kipf·in/ft" } } ] @@ -70,11 +70,11 @@ "PluralName": "PoundForceFeetPerFoot", "FromUnitToBaseFunc": "x*4.44822161526", "FromBaseToUnitFunc": "x/4.44822161526", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["lbf·ft/ft"], + "Abbreviations": [ "lbf·ft/ft" ], "AbbreviationsForPrefixes": { "Kilo": "kipf·ft/ft" } } ] @@ -87,7 +87,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf·mm/m"] + "Abbreviations": [ "kgf·mm/m" ] } ] }, @@ -99,7 +99,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf·cm/m"] + "Abbreviations": [ "kgf·cm/m" ] } ] }, @@ -111,7 +111,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgf·m/m"] + "Abbreviations": [ "kgf·m/m" ] } ] }, @@ -123,7 +123,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf·mm/m"] + "Abbreviations": [ "tf·mm/m" ] } ] }, @@ -135,7 +135,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf·cm/m"] + "Abbreviations": [ "tf·cm/m" ] } ] }, @@ -147,9 +147,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tf·m/m"] + "Abbreviations": [ "tf·m/m" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/VitaminA.json b/Common/UnitDefinitions/VitaminA.json index 8e549febad..b503e93f3b 100644 --- a/Common/UnitDefinitions/VitaminA.json +++ b/Common/UnitDefinitions/VitaminA.json @@ -12,7 +12,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["IU"] + "Abbreviations": [ "IU" ] } ] } diff --git a/Common/UnitDefinitions/Volume.json b/Common/UnitDefinitions/Volume.json index 1098516672..d2e87ac4b2 100644 --- a/Common/UnitDefinitions/Volume.json +++ b/Common/UnitDefinitions/Volume.json @@ -1,8 +1,7 @@ { "Name": "Volume", "BaseUnit": "CubicMeter", - "XmlDoc": - "Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces.", + "XmlDoc": "Volume is the quantity of three-dimensional space enclosed by some closed boundary, for example, the space that a substance (solid, liquid, gas, or plasma) or shape occupies or contains.[1] Volume is often quantified numerically using the SI derived unit, the cubic metre. The volume of a container is generally understood to be the capacity of the container, i. e. the amount of fluid (gas or liquid) that the container could hold, rather than the amount of space the container itself displaces.", "BaseDimensions": { "L": 3 }, @@ -12,15 +11,15 @@ "PluralName": "Liters", "FromUnitToBaseFunc": "x/1e3", "FromBaseToUnitFunc": "x*1e3", - "Prefixes": ["Micro", "Milli", "Centi", "Deci", "Hecto", "Kilo", "Mega"], + "Prefixes": [ "Micro", "Milli", "Centi", "Deci", "Hecto", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["l"] + "Abbreviations": [ "l" ] }, { "Culture": "ru-RU", - "Abbreviations": ["л"] + "Abbreviations": [ "л" ] } ] }, @@ -29,15 +28,15 @@ "PluralName": "CubicMeters", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Hecto", "Kilo"], + "Prefixes": [ "Hecto", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m³"] + "Abbreviations": [ "m³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["м³"] + "Abbreviations": [ "м³" ] } ] }, @@ -49,11 +48,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["km³"] + "Abbreviations": [ "km³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["км³"] + "Abbreviations": [ "км³" ] } ] }, @@ -68,15 +67,15 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["hm³"] + "Abbreviations": [ "hm³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["гм³"] + "Abbreviations": [ "гм³" ] } ] }, - { + { "SingularName": "CubicDecimeter", "PluralName": "CubicDecimeters", "FromUnitToBaseFunc": "x/1e3", @@ -84,11 +83,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dm³"] + "Abbreviations": [ "dm³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["дм³"] + "Abbreviations": [ "дм³" ] } ] }, @@ -100,11 +99,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cm³"] + "Abbreviations": [ "cm³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["см³"] + "Abbreviations": [ "см³" ] } ] }, @@ -116,11 +115,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mm³"] + "Abbreviations": [ "mm³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["мм³"] + "Abbreviations": [ "мм³" ] } ] }, @@ -132,11 +131,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["µm³"] + "Abbreviations": [ "µm³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["мкм³"] + "Abbreviations": [ "мкм³" ] } ] }, @@ -148,11 +147,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mi³"] + "Abbreviations": [ "mi³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["миля³"] + "Abbreviations": [ "миля³" ] } ] }, @@ -164,11 +163,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["yd³"] + "Abbreviations": [ "yd³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["ярд³"] + "Abbreviations": [ "ярд³" ] } ] }, @@ -177,15 +176,15 @@ "PluralName": "CubicFeet", "FromUnitToBaseFunc": "x*0.0283168", "FromBaseToUnitFunc": "x/0.0283168", - "Prefixes": ["Hecto", "Kilo", "Mega"], + "Prefixes": [ "Hecto", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft³"] + "Abbreviations": [ "ft³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["фут³"] + "Abbreviations": [ "фут³" ] } ] }, @@ -197,11 +196,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["in³"] + "Abbreviations": [ "in³" ] }, { "Culture": "ru-RU", - "Abbreviations": ["дюйм³"] + "Abbreviations": [ "дюйм³" ] } ] }, @@ -210,15 +209,15 @@ "PluralName": "ImperialGallons", "FromUnitToBaseFunc": "x*0.00454609000000181429905810072407", "FromBaseToUnitFunc": "x/0.00454609000000181429905810072407", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gal (imp.)"] + "Abbreviations": [ "gal (imp.)" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Английский галлон"] + "Abbreviations": [ "Английский галлон" ] } ] }, @@ -230,11 +229,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["oz (imp.)"] + "Abbreviations": [ "oz (imp.)" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Английская унция"] + "Abbreviations": [ "Английская унция" ] } ] }, @@ -243,15 +242,15 @@ "PluralName": "UsGallons", "FromUnitToBaseFunc": "x*0.00378541", "FromBaseToUnitFunc": "x/0.00378541", - "Prefixes": ["Kilo", "Mega"], + "Prefixes": [ "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gal (U.S.)"] + "Abbreviations": [ "gal (U.S.)" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Американский галлон"] + "Abbreviations": [ "Американский галлон" ] } ] }, @@ -263,11 +262,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["oz (U.S.)"] + "Abbreviations": [ "oz (U.S.)" ] }, { "Culture": "ru-RU", - "Abbreviations": ["Американская унция"] + "Abbreviations": [ "Американская унция" ] } ] }, @@ -339,7 +338,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["tsp", "t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon"] + "Abbreviations": [ "tsp", "t", "ts", "tspn", "t.", "ts.", "tsp.", "tspn.", "teaspoon" ] }, { "Culture": "ru-RU", @@ -415,7 +414,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bbl"] + "Abbreviations": [ "bbl" ] } ] }, @@ -427,7 +426,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bl (U.S.)"] + "Abbreviations": [ "bl (U.S.)" ] } ] }, @@ -439,7 +438,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bl (imp.)"] + "Abbreviations": [ "bl (imp.)" ] } ] }, @@ -451,7 +450,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["qt (U.S.)"] + "Abbreviations": [ "qt (U.S.)" ] } ] }, @@ -463,7 +462,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["pt (U.S.)"] + "Abbreviations": [ "pt (U.S.)" ] } ] }, @@ -475,7 +474,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ac-ft", "acre-foot", "acre-feet"] + "Abbreviations": [ "ac-ft", "acre-foot", "acre-feet" ] } ] }, @@ -490,9 +489,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["pt (imp.)", "UK pt", "pt", "p"] + "Abbreviations": [ "pt (imp.)", "UK pt", "pt", "p" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/VolumeConcentration.json b/Common/UnitDefinitions/VolumeConcentration.json index 44ab1f85f0..de56f8491f 100644 --- a/Common/UnitDefinitions/VolumeConcentration.json +++ b/Common/UnitDefinitions/VolumeConcentration.json @@ -1,11 +1,10 @@ { "Name": "VolumeConcentration", "BaseUnit": "DecimalFraction", - "XmlDoc": - "The volume concentration (not to be confused with volume fraction) is defined as the volume of a constituent divided by the total volume of the mixture.", + "XmlDoc": "The volume concentration (not to be confused with volume fraction) is defined as the volume of a constituent divided by the total volume of the mixture.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Concentration#Volume_concentration", "Units": [ - { + { "SingularName": "DecimalFraction", "PluralName": "DecimalFractions", "FromUnitToBaseFunc": "x", @@ -13,33 +12,33 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": [""] + "Abbreviations": [ "" ] } ] }, - { + { "SingularName": "LitersPerLiter", "PluralName": "LitersPerLiter", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["L/L"] + "Abbreviations": [ "L/L" ] } ] }, - { + { "SingularName": "LitersPerMililiter", "PluralName": "LitersPerMililiter", "FromUnitToBaseFunc": "x/1e-3", "FromBaseToUnitFunc": "x*1e-3", - "Prefixes": ["Pico", "Nano", "Micro", "Milli", "Centi", "Deci"], + "Prefixes": [ "Pico", "Nano", "Micro", "Milli", "Centi", "Deci" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["L/mL"] + "Abbreviations": [ "L/mL" ] } ] }, @@ -51,7 +50,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["%", "% (v/v)"] + "Abbreviations": [ "%", "% (v/v)" ] } ] }, @@ -63,7 +62,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["‰"] + "Abbreviations": [ "‰" ] } ] }, @@ -75,7 +74,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppm"] + "Abbreviations": [ "ppm" ] } ] }, @@ -87,7 +86,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppb"] + "Abbreviations": [ "ppb" ] } ] }, @@ -99,7 +98,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ppt"] + "Abbreviations": [ "ppt" ] } ] } diff --git a/Common/UnitDefinitions/VolumeFlow.json b/Common/UnitDefinitions/VolumeFlow.json index db5e20c620..6528c99c98 100644 --- a/Common/UnitDefinitions/VolumeFlow.json +++ b/Common/UnitDefinitions/VolumeFlow.json @@ -1,8 +1,7 @@ { "Name": "VolumeFlow", "BaseUnit": "CubicMeterPerSecond", - "XmlDoc": - "In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q.", + "XmlDoc": "In physics and engineering, in particular fluid dynamics and hydrometry, the volumetric flow rate, (also known as volume flow rate, rate of fluid flow or volume velocity) is the volume of fluid which passes through a given surface per unit time. The SI unit is m³/s (cubic meters per second). In US Customary Units and British Imperial Units, volumetric flow rate is often expressed as ft³/s (cubic feet per second). It is usually represented by the symbol Q.", "BaseDimensions": { "L": 3, "T": -1 @@ -16,11 +15,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m³/s"] + "Abbreviations": [ "m³/s" ] }, { "Culture": "ru-RU", - "Abbreviations": ["м³/с"] + "Abbreviations": [ "м³/с" ] } ] }, @@ -32,7 +31,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m³/min"] + "Abbreviations": [ "m³/min" ] } ] }, @@ -44,11 +43,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m³/h"] + "Abbreviations": [ "m³/h" ] }, { "Culture": "ru-RU", - "Abbreviations": ["м³/ч"] + "Abbreviations": [ "м³/ч" ] } ] }, @@ -60,7 +59,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m³/d"] + "Abbreviations": [ "m³/d" ] } ] }, @@ -72,7 +71,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft³/s"] + "Abbreviations": [ "ft³/s" ] } ] }, @@ -84,7 +83,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft³/min"] + "Abbreviations": [ "ft³/min" ] } ] }, @@ -96,7 +95,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["ft³/h", "cf/hr"] + "Abbreviations": [ "ft³/h", "cf/hr" ] } ] }, @@ -108,7 +107,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["yd³/s"] + "Abbreviations": [ "yd³/s" ] } ] }, @@ -120,7 +119,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["yd³/min"] + "Abbreviations": [ "yd³/min" ] } ] }, @@ -132,7 +131,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["yd³/h"] + "Abbreviations": [ "yd³/h" ] } ] }, @@ -144,7 +143,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["cy/day"] + "Abbreviations": [ "cy/day" ] } ] }, @@ -156,7 +155,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["MGD"] + "Abbreviations": [ "MGD" ] } ] }, @@ -168,7 +167,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gpd", "gal/d"] + "Abbreviations": [ "gpd", "gal/d" ] } ] }, @@ -180,7 +179,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["L/s", "LPS"] + "Abbreviations": [ "L/s", "LPS" ] } ] }, @@ -189,11 +188,11 @@ "PluralName": "LitersPerMinute", "FromUnitToBaseFunc": "x/60000.00000", "FromBaseToUnitFunc": "x*60000.00000", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["L/min", "LPM"] + "Abbreviations": [ "L/min", "LPM" ] } ] }, @@ -205,11 +204,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["L/h", "LPH"] + "Abbreviations": [ "L/h", "LPH" ] }, { "Culture": "ru-RU", - "Abbreviations": ["л/ч"] + "Abbreviations": [ "л/ч" ] } ] }, @@ -218,11 +217,11 @@ "PluralName": "LitersPerDay", "FromUnitToBaseFunc": "x/86400000", "FromBaseToUnitFunc": "x*86400000", - "Prefixes": ["Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega"], + "Prefixes": [ "Nano", "Micro", "Milli", "Centi", "Deci", "Kilo", "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["l/day", "L/d", "LPD"] + "Abbreviations": [ "l/day", "L/d", "LPD" ] } ] }, @@ -234,7 +233,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gal (U.S.)/s"] + "Abbreviations": [ "gal (U.S.)/s" ] } ] }, @@ -246,7 +245,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gal (U.S.)/min", "GPM"] + "Abbreviations": [ "gal (U.S.)/min", "GPM" ] } ] }, @@ -258,7 +257,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gal (U. K.)/d"] + "Abbreviations": [ "gal (U. K.)/d" ] } ] }, @@ -270,7 +269,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gal (imp.)/h"] + "Abbreviations": [ "gal (imp.)/h" ] } ] }, @@ -282,7 +281,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gal (imp.)/min"] + "Abbreviations": [ "gal (imp.)/min" ] } ] }, @@ -291,11 +290,11 @@ "PluralName": "UkGallonsPerSecond", "FromUnitToBaseFunc": "x/219.969", "FromBaseToUnitFunc": "x*219.969", - "Prefixes": ["Mega"], + "Prefixes": [ "Mega" ], "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gal (imp.)/s"] + "Abbreviations": [ "gal (imp.)/s" ] } ] }, @@ -307,7 +306,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["kgal (U.S.)/min", "KGPM"] + "Abbreviations": [ "kgal (U.S.)/min", "KGPM" ] } ] }, @@ -319,7 +318,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["gal (U.S.)/h"] + "Abbreviations": [ "gal (U.S.)/h" ] } ] }, @@ -331,11 +330,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["dm³/min"] + "Abbreviations": [ "dm³/min" ] }, { "Culture": "ru-RU", - "Abbreviations": ["дм³/мин"] + "Abbreviations": [ "дм³/мин" ] } ] }, @@ -347,7 +346,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bbl/d", "BOPD"] + "Abbreviations": [ "bbl/d", "BOPD" ] } ] }, @@ -359,7 +358,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bbl/min", "bpm"] + "Abbreviations": [ "bbl/min", "bpm" ] } ] }, @@ -371,7 +370,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bbl/hr", "bph"] + "Abbreviations": [ "bbl/hr", "bph" ] } ] }, @@ -383,7 +382,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bbl/s"] + "Abbreviations": [ "bbl/s" ] } ] }, @@ -395,11 +394,11 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["mm³/s"] + "Abbreviations": [ "mm³/s" ] }, { "Culture": "ru-RU", - "Abbreviations": ["мм³/с"] + "Abbreviations": [ "мм³/с" ] } ] }, @@ -411,7 +410,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["af/s"] + "Abbreviations": [ "af/s" ] } ] }, @@ -423,7 +422,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["af/m"] + "Abbreviations": [ "af/m" ] } ] }, @@ -435,7 +434,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["af/h"] + "Abbreviations": [ "af/h" ] } ] }, @@ -447,9 +446,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["af/d"] + "Abbreviations": [ "af/d" ] } ] } ] -} \ No newline at end of file +} diff --git a/Common/UnitDefinitions/VolumePerLength.json b/Common/UnitDefinitions/VolumePerLength.json index 73bd8e4f85..2098ba6030 100644 --- a/Common/UnitDefinitions/VolumePerLength.json +++ b/Common/UnitDefinitions/VolumePerLength.json @@ -18,7 +18,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["m³/m"] + "Abbreviations": [ "m³/m" ] } ] }, @@ -34,7 +34,7 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["l/m"] + "Abbreviations": [ "l/m" ] } ] }, @@ -47,9 +47,9 @@ "Localization": [ { "Culture": "en-US", - "Abbreviations": ["bbl/ft"] + "Abbreviations": [ "bbl/ft" ] } ] } ] -} \ No newline at end of file +} diff --git a/UnitsNet.Benchmark/Program.cs b/UnitsNet.Benchmark/Program.cs index a7a45e6c7f..d51d42b653 100644 --- a/UnitsNet.Benchmark/Program.cs +++ b/UnitsNet.Benchmark/Program.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; using UnitsNet.Units; @@ -11,7 +8,7 @@ namespace UnitsNet.Benchmark public class UnitsNetBenchmarks { private Length length = Length.FromMeters(3.0); - private readonly IQuantity lengthIQuantity = Length.FromMeters(3.0); + private IQuantity lengthIQuantity = Length.FromMeters(3.0); [Benchmark] public Length Constructor() => new Length(3.0, LengthUnit.Meter); @@ -65,9 +62,9 @@ public class UnitsNetBenchmarks public string IQuantity_ToStringTest() => lengthIQuantity.ToString(); } - internal class Program + class Program { - private static void Main(string[] args) + static void Main(string[] args) { var summary = BenchmarkRunner.Run(); } diff --git a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs index e7c7ac0a9c..0a62526b9c 100644 --- a/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs +++ b/UnitsNet.Serialization.JsonNet.CompatibilityTests/UnitsNetJsonConverterTests.cs @@ -29,67 +29,35 @@ private T DeserializeObject(string json) public class Serialize : UnitsNetJsonConverterTests { - [Fact(Skip = "Not supported in older versions of serialization")] - public void ArrayValue_ExpectJsonArray() - { - Frequency[] testObj = {Frequency.FromHertz(10), Frequency.FromHertz(10)}; - - var expectedJson = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; - - var json = SerializeObject(testObj); - - Assert.Equal(expectedJson, json); - } - - [Fact(Skip = "Not supported in older versions of serialization")] - public void EmptyArrayValue_ExpectJsonArray() - { - var testObj = new Frequency[0]; - - var expectedJson = "[]"; - - var json = SerializeObject(testObj); - Assert.Equal(expectedJson, json); - } - [Fact] public void Information_CanSerializeVeryLargeValues() { - var i = Information.FromExabytes(1E+9); + Information i = Information.FromExabytes(1E+9); var expectedJson = "{\n \"Unit\": \"InformationUnit.Exabyte\",\n \"Value\": 1000000000.0\n}"; - var json = SerializeObject(i); + string json = SerializeObject(i); Assert.Equal(expectedJson, json); } [Fact] - public void Information_ExpectConstructedValueAndUnit() + public void Mass_ExpectConstructedValueAndUnit() { - var quantity = Information.FromKilobytes(54); - var expectedJson = "{\n \"Unit\": \"InformationUnit.Kilobyte\",\n \"Value\": 54.0\n}"; + Mass mass = Mass.FromPounds(200); + var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; - var json = SerializeObject(quantity); + string json = SerializeObject(mass); Assert.Equal(expectedJson, json); } [Fact] - public void Mass_ExpectConstructedValueAndUnit() + public void Information_ExpectConstructedValueAndUnit() { - var mass = Mass.FromPounds(200); - var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; + Information quantity = Information.FromKilobytes(54); + var expectedJson = "{\n \"Unit\": \"InformationUnit.Kilobyte\",\n \"Value\": 54.0\n}"; - var json = SerializeObject(mass); + string json = SerializeObject(quantity); Assert.Equal(expectedJson, json); } @@ -100,7 +68,7 @@ public void NonNullNullableValue_ExpectJsonUnaffected() Mass? nullableMass = Mass.FromKilograms(10); var expectedJson = "{\n \"Unit\": \"MassUnit.Kilogram\",\n \"Value\": 10.0\n}"; - var json = SerializeObject(nullableMass); + string json = SerializeObject(nullableMass); // There shouldn't be any change in the JSON for the non-null nullable value. Assert.Equal(expectedJson, json); @@ -109,21 +77,25 @@ public void NonNullNullableValue_ExpectJsonUnaffected() [Fact] public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() { - var testObj = new TestObj {NullableFrequency = Frequency.FromHertz(10), NonNullableFrequency = Frequency.FromHertz(10)}; + var testObj = new TestObj + { + NullableFrequency = Frequency.FromHertz(10), + NonNullableFrequency = Frequency.FromHertz(10) + }; // Ugly manually formatted JSON string is used because string literals with newlines are rendered differently // on the build server (i.e. the build server uses '\r' instead of '\n') - var expectedJson = "{\n" + - " \"NullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " \"NonNullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "}"; - - var json = SerializeObject(testObj); + string expectedJson = "{\n" + + " \"NullableFrequency\": {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " \"NonNullableFrequency\": {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "}"; + + string json = SerializeObject(testObj); Assert.Equal(expectedJson, json); } @@ -131,94 +103,61 @@ public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() [Fact] public void NullValue_ExpectJsonContainsNullString() { - var json = SerializeObject(null); + string json = SerializeObject(null); Assert.Equal("null", json); } [Fact] public void Ratio_ExpectDecimalFractionsUsedAsBaseValueAndUnit() { - var ratio = Ratio.FromPartsPerThousand(250); + Ratio ratio = Ratio.FromPartsPerThousand(250); var expectedJson = "{\n \"Unit\": \"RatioUnit.PartPerThousand\",\n \"Value\": 250.0\n}"; - var json = SerializeObject(ratio); + string json = SerializeObject(ratio); Assert.Equal(expectedJson, json); } - } - - public class Deserialize : UnitsNetJsonConverterTests - { - private static JsonSerializerSettings CreateJsonSerializerSettings() - { - var jsonSerializerSettings = new JsonSerializerSettings {Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.Auto}; - jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); - return jsonSerializerSettings; - } [Fact(Skip = "Not supported in older versions of serialization")] - public void ArrayOfUnits_ExpectCorrectlyDeserialized() - { - Frequency[] expected = {Frequency.FromHertz(10), Frequency.FromHertz(10)}; - - var json = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; - - var result = DeserializeObject(json); - - Assert.Equal(expected, result); - } - - [Fact] - public void ClassInIComparable_ExpectUnitCorrectlyDeserialized() - { - var testObjWithIComparable = new TestObjWithIComparable {Value = new ComparableClass {Value = 10}}; - var jsonSerializerSettings = CreateJsonSerializerSettings(); - - var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, ((ComparableClass) deserializedTestObject.Value).Value); - } - - [Fact] - public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized() + public void ArrayValue_ExpectJsonArray() { - var testObjWithIComparable = new TestObjWithIComparable {Value = 10.0}; - var jsonSerializerSettings = CreateJsonSerializerSettings(); + Frequency[] testObj = new Frequency[] { Frequency.FromHertz(10), Frequency.FromHertz(10) }; - var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + string expectedJson = "[\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "]"; - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + string json = SerializeObject(testObj); - Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, (double) deserializedTestObject.Value); + Assert.Equal(expectedJson, json); } [Fact(Skip = "Not supported in older versions of serialization")] - public void EmptyArray_ExpectCorrectlyDeserialized() + public void EmptyArrayValue_ExpectJsonArray() { - var json = "[]"; + Frequency[] testObj = new Frequency[0]; - var result = DeserializeObject(json); + string expectedJson = "[]"; - Assert.Empty(result); + string json = SerializeObject(testObj); + Assert.Equal(expectedJson, json); } + } + public class Deserialize : UnitsNetJsonConverterTests + { [Fact] public void Information_CanDeserializeVeryLargeValues() { - var original = Information.FromExabytes(1E+9); - var json = SerializeObject(original); + Information original = Information.FromExabytes(1E+9); + string json = SerializeObject(original); var deserialized = DeserializeObject(json); Assert.Equal(original, deserialized); @@ -227,8 +166,8 @@ public void Information_CanDeserializeVeryLargeValues() [Fact] public void Mass_ExpectJsonCorrectlyDeserialized() { - var originalMass = Mass.FromKilograms(33.33); - var json = SerializeObject(originalMass); + Mass originalMass = Mass.FromKilograms(33.33); + string json = SerializeObject(originalMass); var deserializedMass = DeserializeObject(json); @@ -239,9 +178,9 @@ public void Mass_ExpectJsonCorrectlyDeserialized() public void NonNullNullableValue_ExpectValueDeserializedCorrectly() { Mass? nullableMass = Mass.FromKilograms(10); - var json = SerializeObject(nullableMass); + string json = SerializeObject(nullableMass); - var deserializedNullableMass = DeserializeObject(json); + Mass? deserializedNullableMass = DeserializeObject(json); Assert.Equal(nullableMass.Value, deserializedNullableMass); } @@ -249,8 +188,12 @@ public void NonNullNullableValue_ExpectValueDeserializedCorrectly() [Fact] public void NonNullNullableValueNestedInObject_ExpectValueDeserializedCorrectly() { - var testObj = new TestObj {NullableFrequency = Frequency.FromHertz(10), NonNullableFrequency = Frequency.FromHertz(10)}; - var json = SerializeObject(testObj); + var testObj = new TestObj + { + NullableFrequency = Frequency.FromHertz(10), + NonNullableFrequency = Frequency.FromHertz(10) + }; + string json = SerializeObject(testObj); var deserializedTestObj = DeserializeObject(json); @@ -260,7 +203,7 @@ public void NonNullNullableValueNestedInObject_ExpectValueDeserializedCorrectly( [Fact] public void NullValue_ExpectNullReturned() { - var json = SerializeObject(null); + string json = SerializeObject(null); var deserializedNullMass = DeserializeObject(json); Assert.Null(deserializedNullMass); @@ -269,22 +212,96 @@ public void NullValue_ExpectNullReturned() [Fact] public void NullValueNestedInObject_ExpectValueDeserializedToNullCorrectly() { - var testObj = new TestObj {NullableFrequency = null, NonNullableFrequency = Frequency.FromHertz(10)}; - var json = SerializeObject(testObj); + var testObj = new TestObj + { + NullableFrequency = null, + NonNullableFrequency = Frequency.FromHertz(10) + }; + string json = SerializeObject(testObj); var deserializedTestObj = DeserializeObject(json); Assert.Null(deserializedTestObj.NullableFrequency); } + [Fact] + public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized() + { + Mass originalMass = Mass.FromKilograms(33.33); + string json = SerializeObject(originalMass); + // Someone manually changed the serialized JSON string to 1000 grams. + json = json.Replace("33.33", "1000"); + json = json.Replace("MassUnit.Kilogram", "MassUnit.Gram"); + + var deserializedMass = DeserializeObject(json); + + // The original value serialized was 33.33 kg, but someone edited the JSON to be 1000 g. We expect the JSON is + // still deserializable, and the correct value of 1000 g is obtained. + Assert.Equal(1000, deserializedMass.Grams); + } + + [Fact] + public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() + { + TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() + { + Value = Power.FromWatts(10) + }; + JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); + + string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + + var deserializedTestObject = JsonConvert.DeserializeObject(json,jsonSerializerSettings); + + Assert.Equal(typeof(Power), deserializedTestObject.Value.GetType()); + Assert.Equal(Power.FromWatts(10), (Power)deserializedTestObject.Value); + } + + [Fact] + public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized() + { + TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() + { + Value = 10.0 + }; + JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); + + string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + + Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); + Assert.Equal(10d, (double)deserializedTestObject.Value); + } + + [Fact] + public void ClassInIComparable_ExpectUnitCorrectlyDeserialized() + { + TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() + { + Value = new ComparableClass() { Value = 10 } + }; + JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); + + string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + + Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value.GetType()); + Assert.Equal(10d, ((ComparableClass) deserializedTestObject.Value).Value); + } + [Fact] public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues() { - var testObjWithValueAndUnit = new TestObjWithValueAndUnit {Value = 5, Unit = "Test"}; - var jsonSerializerSettings = CreateJsonSerializerSettings(); + TestObjWithValueAndUnit testObjWithValueAndUnit = new TestObjWithValueAndUnit() + { + Value = 5, + Unit = "Test", + }; + JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - var json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + string json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings); + TestObjWithValueAndUnit deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); Assert.Equal(5d, deserializedTestObject.Value); @@ -294,13 +311,15 @@ public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues() [Fact] public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeserialized() { - var testObjWithIComparable = new TestObjWithThreeIComparable + TestObjWithThreeIComparable testObjWithIComparable = new TestObjWithThreeIComparable() { - Value1 = 10.0, Value2 = Power.FromWatts(19), Value3 = new ComparableClass {Value = 10} + Value1 = 10.0, + Value2 = Power.FromWatts(19), + Value3 = new ComparableClass() { Value = 10 }, }; - var jsonSerializerSettings = CreateJsonSerializerSettings(); + JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); Assert.Equal(typeof(double), deserializedTestObject.Value1.GetType()); @@ -311,34 +330,46 @@ public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeser Assert.Equal(testObjWithIComparable.Value3, deserializedTestObject.Value3); } - [Fact] - public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized() + [Fact(Skip = "Not supported in older versions of serialization")] + public void ArrayOfUnits_ExpectCorrectlyDeserialized() { - var originalMass = Mass.FromKilograms(33.33); - var json = SerializeObject(originalMass); - // Someone manually changed the serialized JSON string to 1000 grams. - json = json.Replace("33.33", "1000"); - json = json.Replace("MassUnit.Kilogram", "MassUnit.Gram"); + Frequency[] expected = new Frequency[] { Frequency.FromHertz(10), Frequency.FromHertz(10) }; - var deserializedMass = DeserializeObject(json); + string json = "[\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "]"; - // The original value serialized was 33.33 kg, but someone edited the JSON to be 1000 g. We expect the JSON is - // still deserializable, and the correct value of 1000 g is obtained. - Assert.Equal(1000, deserializedMass.Grams); + Frequency[] result = DeserializeObject(json); + + Assert.Equal(expected, result); } - [Fact] - public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() + [Fact(Skip = "Not supported in older versions of serialization")] + public void EmptyArray_ExpectCorrectlyDeserialized() { - var testObjWithIComparable = new TestObjWithIComparable {Value = Power.FromWatts(10)}; - var jsonSerializerSettings = CreateJsonSerializerSettings(); + string json = "[]"; - var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + Frequency[] result = DeserializeObject(json); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + Assert.Empty(result); + } - Assert.Equal(typeof(Power), deserializedTestObject.Value.GetType()); - Assert.Equal(Power.FromWatts(10), (Power) deserializedTestObject.Value); + private static JsonSerializerSettings CreateJsonSerializerSettings() + { + var jsonSerializerSettings = new JsonSerializerSettings() + { + Formatting = Formatting.Indented, + TypeNameHandling = TypeNameHandling.Auto + }; + jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); + return jsonSerializerSettings; } } @@ -355,17 +386,16 @@ private class TestObjWithValueAndUnit : IComparable public int CompareTo(object obj) { - return ((IComparable) Value).CompareTo(obj); + return ((IComparable)Value).CompareTo(obj); } } private class ComparableClass : IComparable { public int Value { get; set; } - public int CompareTo(object obj) { - return ((IComparable) Value).CompareTo(obj); + return ((IComparable)Value).CompareTo(obj); } // Needed for virfying that the deserialized object is the same, should not affect the serilization code @@ -375,8 +405,7 @@ public override bool Equals(object obj) { return false; } - - return Value.Equals(((ComparableClass) obj).Value); + return Value.Equals(((ComparableClass)obj).Value); } public override int GetHashCode() diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs index 86483ae085..8cb662fe22 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs @@ -29,67 +29,35 @@ private T DeserializeObject(string json) public class Serialize : UnitsNetJsonConverterTests { - [Fact] - public void ArrayValue_ExpectJsonArray() - { - Frequency[] testObj = {Frequency.FromHertz(10), Frequency.FromHertz(10)}; - - var expectedJson = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; - - var json = SerializeObject(testObj); - - Assert.Equal(expectedJson, json); - } - - [Fact] - public void EmptyArrayValue_ExpectJsonArray() - { - var testObj = new Frequency[0]; - - var expectedJson = "[]"; - - var json = SerializeObject(testObj); - Assert.Equal(expectedJson, json); - } - [Fact] public void Information_CanSerializeVeryLargeValues() { - var i = Information.FromExabytes(1E+9); + Information i = Information.FromExabytes(1E+9); var expectedJson = "{\n \"Unit\": \"InformationUnit.Exabyte\",\n \"Value\": 1000000000.0\n}"; - var json = SerializeObject(i); + string json = SerializeObject(i); Assert.Equal(expectedJson, json); } [Fact] - public void Information_ExpectConstructedValueAndUnit() + public void Mass_ExpectConstructedValueAndUnit() { - var quantity = Information.FromKilobytes(54); - var expectedJson = "{\n \"Unit\": \"InformationUnit.Kilobyte\",\n \"Value\": 54.0\n}"; + Mass mass = Mass.FromPounds(200); + var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; - var json = SerializeObject(quantity); + string json = SerializeObject(mass); Assert.Equal(expectedJson, json); } [Fact] - public void Mass_ExpectConstructedValueAndUnit() + public void Information_ExpectConstructedValueAndUnit() { - var mass = Mass.FromPounds(200); - var expectedJson = "{\n \"Unit\": \"MassUnit.Pound\",\n \"Value\": 200.0\n}"; + Information quantity = Information.FromKilobytes(54); + var expectedJson = "{\n \"Unit\": \"InformationUnit.Kilobyte\",\n \"Value\": 54.0\n}"; - var json = SerializeObject(mass); + string json = SerializeObject(quantity); Assert.Equal(expectedJson, json); } @@ -100,7 +68,7 @@ public void NonNullNullableValue_ExpectJsonUnaffected() Mass? nullableMass = Mass.FromKilograms(10); var expectedJson = "{\n \"Unit\": \"MassUnit.Kilogram\",\n \"Value\": 10.0\n}"; - var json = SerializeObject(nullableMass); + string json = SerializeObject(nullableMass); // There shouldn't be any change in the JSON for the non-null nullable value. Assert.Equal(expectedJson, json); @@ -109,21 +77,25 @@ public void NonNullNullableValue_ExpectJsonUnaffected() [Fact] public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() { - var testObj = new TestObj {NullableFrequency = Frequency.FromHertz(10), NonNullableFrequency = Frequency.FromHertz(10)}; + var testObj = new TestObj + { + NullableFrequency = Frequency.FromHertz(10), + NonNullableFrequency = Frequency.FromHertz(10) + }; // Ugly manually formatted JSON string is used because string literals with newlines are rendered differently // on the build server (i.e. the build server uses '\r' instead of '\n') - var expectedJson = "{\n" + - " \"NullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " \"NonNullableFrequency\": {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "}"; - - var json = SerializeObject(testObj); + string expectedJson = "{\n" + + " \"NullableFrequency\": {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " \"NonNullableFrequency\": {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "}"; + + string json = SerializeObject(testObj); Assert.Equal(expectedJson, json); } @@ -131,94 +103,61 @@ public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() [Fact] public void NullValue_ExpectJsonContainsNullString() { - var json = SerializeObject(null); + string json = SerializeObject(null); Assert.Equal("null", json); } [Fact] public void Ratio_ExpectDecimalFractionsUsedAsBaseValueAndUnit() { - var ratio = Ratio.FromPartsPerThousand(250); + Ratio ratio = Ratio.FromPartsPerThousand(250); var expectedJson = "{\n \"Unit\": \"RatioUnit.PartPerThousand\",\n \"Value\": 250.0\n}"; - var json = SerializeObject(ratio); + string json = SerializeObject(ratio); Assert.Equal(expectedJson, json); } - } - - public class Deserialize : UnitsNetJsonConverterTests - { - private static JsonSerializerSettings CreateJsonSerializerSettings() - { - var jsonSerializerSettings = new JsonSerializerSettings {Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.Auto}; - jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); - return jsonSerializerSettings; - } - - [Fact] - public void ArrayOfUnits_ExpectCorrectlyDeserialized() - { - Frequency[] expected = {Frequency.FromHertz(10), Frequency.FromHertz(10)}; - - var json = "[\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " },\n" + - " {\n" + - " \"Unit\": \"FrequencyUnit.Hertz\",\n" + - " \"Value\": 10.0\n" + - " }\n" + - "]"; - - var result = DeserializeObject(json); - - Assert.Equal(expected, result); - } [Fact] - public void ClassInIComparable_ExpectUnitCorrectlyDeserialized() - { - var testObjWithIComparable = new TestObjWithIComparable {Value = new ComparableClass {Value = 10}}; - var jsonSerializerSettings = CreateJsonSerializerSettings(); - - var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); - - Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, ((ComparableClass) deserializedTestObject.Value).Value); - } - - [Fact] - public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized() + public void ArrayValue_ExpectJsonArray() { - var testObjWithIComparable = new TestObjWithIComparable {Value = 10.0}; - var jsonSerializerSettings = CreateJsonSerializerSettings(); + Frequency[] testObj = { Frequency.FromHertz(10), Frequency.FromHertz(10) }; - var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + string expectedJson = "[\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "]"; - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + string json = SerializeObject(testObj); - Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); - Assert.Equal(10d, (double) deserializedTestObject.Value); + Assert.Equal(expectedJson, json); } [Fact] - public void EmptyArray_ExpectCorreclyDeserialized() + public void EmptyArrayValue_ExpectJsonArray() { - var json = "[]"; + Frequency[] testObj = new Frequency[0]; - var result = DeserializeObject(json); + string expectedJson = "[]"; - Assert.Empty(result); + string json = SerializeObject(testObj); + Assert.Equal(expectedJson, json); } + } + public class Deserialize : UnitsNetJsonConverterTests + { [Fact] public void Information_CanDeserializeVeryLargeValues() { - var original = Information.FromExabytes(1E+9); - var json = SerializeObject(original); + Information original = Information.FromExabytes(1E+9); + string json = SerializeObject(original); var deserialized = DeserializeObject(json); Assert.Equal(original, deserialized); @@ -227,8 +166,8 @@ public void Information_CanDeserializeVeryLargeValues() [Fact] public void Mass_ExpectJsonCorrectlyDeserialized() { - var originalMass = Mass.FromKilograms(33.33); - var json = SerializeObject(originalMass); + Mass originalMass = Mass.FromKilograms(33.33); + string json = SerializeObject(originalMass); var deserializedMass = DeserializeObject(json); @@ -239,9 +178,9 @@ public void Mass_ExpectJsonCorrectlyDeserialized() public void NonNullNullableValue_ExpectValueDeserializedCorrectly() { Mass? nullableMass = Mass.FromKilograms(10); - var json = SerializeObject(nullableMass); + string json = SerializeObject(nullableMass); - var deserializedNullableMass = DeserializeObject(json); + Mass? deserializedNullableMass = DeserializeObject(json); Assert.Equal(nullableMass.Value, deserializedNullableMass); } @@ -249,8 +188,12 @@ public void NonNullNullableValue_ExpectValueDeserializedCorrectly() [Fact] public void NonNullNullableValueNestedInObject_ExpectValueDeserializedCorrectly() { - var testObj = new TestObj {NullableFrequency = Frequency.FromHertz(10), NonNullableFrequency = Frequency.FromHertz(10)}; - var json = SerializeObject(testObj); + var testObj = new TestObj + { + NullableFrequency = Frequency.FromHertz(10), + NonNullableFrequency = Frequency.FromHertz(10) + }; + string json = SerializeObject(testObj); var deserializedTestObj = DeserializeObject(json); @@ -260,7 +203,7 @@ public void NonNullNullableValueNestedInObject_ExpectValueDeserializedCorrectly( [Fact] public void NullValue_ExpectNullReturned() { - var json = SerializeObject(null); + string json = SerializeObject(null); var deserializedNullMass = DeserializeObject(json); Assert.Null(deserializedNullMass); @@ -269,22 +212,96 @@ public void NullValue_ExpectNullReturned() [Fact] public void NullValueNestedInObject_ExpectValueDeserializedToNullCorrectly() { - var testObj = new TestObj {NullableFrequency = null, NonNullableFrequency = Frequency.FromHertz(10)}; - var json = SerializeObject(testObj); + var testObj = new TestObj + { + NullableFrequency = null, + NonNullableFrequency = Frequency.FromHertz(10) + }; + string json = SerializeObject(testObj); var deserializedTestObj = DeserializeObject(json); Assert.Null(deserializedTestObj.NullableFrequency); } + [Fact] + public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized() + { + Mass originalMass = Mass.FromKilograms(33.33); + string json = SerializeObject(originalMass); + // Someone manually changed the serialized JSON string to 1000 grams. + json = json.Replace("33.33", "1000"); + json = json.Replace("MassUnit.Kilogram", "MassUnit.Gram"); + + var deserializedMass = DeserializeObject(json); + + // The original value serialized was 33.33 kg, but someone edited the JSON to be 1000 g. We expect the JSON is + // still deserializable, and the correct value of 1000 g is obtained. + Assert.Equal(1000, deserializedMass.Grams); + } + + [Fact] + public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() + { + TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() + { + Value = Power.FromWatts(10) + }; + JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); + + string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + + var deserializedTestObject = JsonConvert.DeserializeObject(json,jsonSerializerSettings); + + Assert.Equal(typeof(Power), deserializedTestObject.Value.GetType()); + Assert.Equal(Power.FromWatts(10), (Power)deserializedTestObject.Value); + } + + [Fact] + public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized() + { + TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() + { + Value = 10.0 + }; + JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); + + string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + + Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); + Assert.Equal(10d, (double)deserializedTestObject.Value); + } + + [Fact] + public void ClassInIComparable_ExpectUnitCorrectlyDeserialized() + { + TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable() + { + Value = new ComparableClass() { Value = 10 } + }; + JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); + + string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + + Assert.Equal(typeof(ComparableClass), deserializedTestObject.Value.GetType()); + Assert.Equal(10d, ((ComparableClass) deserializedTestObject.Value).Value); + } + [Fact] public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues() { - var testObjWithValueAndUnit = new TestObjWithValueAndUnit {Value = 5, Unit = "Test"}; - var jsonSerializerSettings = CreateJsonSerializerSettings(); + TestObjWithValueAndUnit testObjWithValueAndUnit = new TestObjWithValueAndUnit() + { + Value = 5, + Unit = "Test", + }; + JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - var json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + string json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings); + TestObjWithValueAndUnit deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); Assert.Equal(typeof(double), deserializedTestObject.Value.GetType()); Assert.Equal(5d, deserializedTestObject.Value); @@ -294,13 +311,15 @@ public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues() [Fact] public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeserialized() { - var testObjWithIComparable = new TestObjWithThreeIComparable + TestObjWithThreeIComparable testObjWithIComparable = new TestObjWithThreeIComparable() { - Value1 = 10.0, Value2 = Power.FromWatts(19), Value3 = new ComparableClass {Value = 10} + Value1 = 10.0, + Value2 = Power.FromWatts(19), + Value3 = new ComparableClass() { Value = 10 }, }; - var jsonSerializerSettings = CreateJsonSerializerSettings(); + JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettings(); - var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); Assert.Equal(typeof(double), deserializedTestObject.Value1.GetType()); @@ -312,33 +331,45 @@ public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeser } [Fact] - public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized() + public void ArrayOfUnits_ExpectCorrectlyDeserialized() { - var originalMass = Mass.FromKilograms(33.33); - var json = SerializeObject(originalMass); - // Someone manually changed the serialized JSON string to 1000 grams. - json = json.Replace("33.33", "1000"); - json = json.Replace("MassUnit.Kilogram", "MassUnit.Gram"); + Frequency[] expected = { Frequency.FromHertz(10), Frequency.FromHertz(10) }; - var deserializedMass = DeserializeObject(json); + string json = "[\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " },\n" + + " {\n" + + " \"Unit\": \"FrequencyUnit.Hertz\",\n" + + " \"Value\": 10.0\n" + + " }\n" + + "]"; - // The original value serialized was 33.33 kg, but someone edited the JSON to be 1000 g. We expect the JSON is - // still deserializable, and the correct value of 1000 g is obtained. - Assert.Equal(1000, deserializedMass.Grams); + Frequency[] result = DeserializeObject(json); + + Assert.Equal(expected, result); } [Fact] - public void UnitInIComparable_ExpectUnitCorrectlyDeserialized() + public void EmptyArray_ExpectCorreclyDeserialized() { - var testObjWithIComparable = new TestObjWithIComparable {Value = Power.FromWatts(10)}; - var jsonSerializerSettings = CreateJsonSerializerSettings(); + string json = "[]"; - var json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings); + Frequency[] result = DeserializeObject(json); - var deserializedTestObject = JsonConvert.DeserializeObject(json, jsonSerializerSettings); + Assert.Empty(result); + } - Assert.Equal(typeof(Power), deserializedTestObject.Value.GetType()); - Assert.Equal(Power.FromWatts(10), (Power) deserializedTestObject.Value); + private static JsonSerializerSettings CreateJsonSerializerSettings() + { + var jsonSerializerSettings = new JsonSerializerSettings() + { + Formatting = Formatting.Indented, + TypeNameHandling = TypeNameHandling.Auto + }; + jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter()); + return jsonSerializerSettings; } } @@ -355,17 +386,16 @@ private class TestObjWithValueAndUnit : IComparable public int CompareTo(object obj) { - return ((IComparable) Value).CompareTo(obj); + return ((IComparable)Value).CompareTo(obj); } } private class ComparableClass : IComparable { public int Value { get; set; } - public int CompareTo(object obj) { - return ((IComparable) Value).CompareTo(obj); + return ((IComparable)Value).CompareTo(obj); } // Needed for virfying that the deserialized object is the same, should not affect the serilization code @@ -375,8 +405,7 @@ public override bool Equals(object obj) { return false; } - - return Value.Equals(((ComparableClass) obj).Value); + return Value.Equals(((ComparableClass)obj).Value); } public override int GetHashCode() diff --git a/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs b/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs index 866600bdb5..930acb1080 100644 --- a/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs +++ b/UnitsNet.Serialization.JsonNet/Internal/ReflectionHelper.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; using System.Collections.Generic; using System.Reflection; @@ -24,23 +21,17 @@ internal static PropertyInfo GetProperty(this Type type, string name) internal static IEnumerable GetDeclaredMethods(this Type someType) { - var t = someType; + Type t = someType; while (t != null) { #if (NET40 || NET35 || NET20 || SILVERLIGHT) foreach (var m in t.GetMethods()) - { yield return m; - } - t = t.BaseType; #else - var ti = t.GetTypeInfo(); - foreach (var m in ti.DeclaredMethods) - { + TypeInfo ti = t.GetTypeInfo(); + foreach (MethodInfo m in ti.DeclaredMethods) yield return m; - } - t = ti.BaseType; #endif } diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs index 215fa8039d..c8c460ccc8 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs @@ -38,11 +38,9 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist JsonSerializer serializer) { if (reader.ValueType != null) - { return reader.Value; - } - var obj = TryDeserializeIComparable(reader, serializer); + object obj = TryDeserializeIComparable(reader, serializer); if (obj is Array values) { // Create array with the requested type, such as `Length[]` or `Frequency[]` @@ -52,32 +50,33 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist var i = 0; foreach (ValueUnit valueUnit in values) { - var quantity = ParseValueUnit(valueUnit); + IQuantity quantity = ParseValueUnit(valueUnit); arrayOfQuantities.SetValue(quantity, i++); } return arrayOfQuantities; } - else if (obj is ValueUnit valueUnit) { return ParseValueUnit(valueUnit); } - - return obj; + else + { + return obj; + } } private static IQuantity ParseValueUnit(ValueUnit vu) { // "MassUnit.Kilogram" => "MassUnit" and "Kilogram" - var unitEnumTypeName = vu.Unit.Split('.')[0]; - var unitEnumValue = vu.Unit.Split('.')[1]; + string unitEnumTypeName = vu.Unit.Split('.')[0]; + string unitEnumValue = vu.Unit.Split('.')[1]; // "UnitsNet.Units.MassUnit,UnitsNet" - var unitEnumTypeAssemblyQualifiedName = "UnitsNet.Units." + unitEnumTypeName + ",UnitsNet"; + string unitEnumTypeAssemblyQualifiedName = "UnitsNet.Units." + unitEnumTypeName + ",UnitsNet"; // -- see http://stackoverflow.com/a/6465096/1256096 for details - var unitEnumType = Type.GetType(unitEnumTypeAssemblyQualifiedName); + Type unitEnumType = Type.GetType(unitEnumTypeAssemblyQualifiedName); if (unitEnumType == null) { var ex = new UnitsNetException("Unable to find enum type."); @@ -85,34 +84,45 @@ private static IQuantity ParseValueUnit(ValueUnit vu) throw ex; } - var value = vu.Value; - var unitValue = (Enum) Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram + double value = vu.Value; + Enum unitValue = (Enum)Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram return Quantity.From(value, unitValue); } private static object TryDeserializeIComparable(JsonReader reader, JsonSerializer serializer) { - var token = JToken.Load(reader); + JToken token = JToken.Load(reader); if (token is JArray) { - var results = token.Children().Select(item => TryDeserializeIComparable(item, serializer)).ToArray(); + object[] results = token.Children().Select(item => TryDeserializeIComparable(item, serializer)).ToArray(); return results; } - - return TryDeserializeIComparable(token, serializer); + else + { + return TryDeserializeIComparable(token, serializer); + } } private static object TryDeserializeIComparable(JToken token, JsonSerializer serializer) { if (!token.HasValues || token[nameof(ValueUnit.Unit)] == null || token[nameof(ValueUnit.Value)] == null) { - var localSerializer = new JsonSerializer {TypeNameHandling = serializer.TypeNameHandling}; + var localSerializer = new JsonSerializer + { + TypeNameHandling = serializer.TypeNameHandling, + }; return token.ToObject(localSerializer); } - - return new ValueUnit {Unit = token[nameof(ValueUnit.Unit)].ToString(), Value = token[nameof(ValueUnit.Value)].ToObject()}; + else + { + return new ValueUnit + { + Unit = token[nameof(ValueUnit.Unit)].ToString(), + Value = token[nameof(ValueUnit.Value)].ToObject() + }; + } } /// @@ -127,7 +137,10 @@ public override void WriteJson(JsonWriter writer, object obj, JsonSerializer ser // ValueUnit should be written as usual (but read in a custom way) if (obj is ValueUnit valueUnit) { - var localSerializer = new JsonSerializer {TypeNameHandling = serializer.TypeNameHandling}; + var localSerializer = new JsonSerializer + { + TypeNameHandling = serializer.TypeNameHandling, + }; var t = JToken.FromObject(valueUnit, localSerializer); t.WriteTo(writer); @@ -152,7 +165,8 @@ private static ValueUnit ToValueUnit(IQuantity value) return new ValueUnit { // See ValueUnit about precision loss for quantities using decimal type. - Value = value.Value, Unit = $"{value.QuantityInfo.UnitType.Name}.{value.Unit}" + Value = value.Value, + Unit = $"{value.QuantityInfo.UnitType.Name}.{value.Unit}" }; } @@ -164,6 +178,7 @@ private static ValueUnit ToValueUnit(IQuantity value) /// in a loss of precision when serializing/deserializing to decimal. /// Decimal is the highest precision type available in .NET, but has a smaller /// range than double. + /// /// Json: Support decimal precision #503 /// https://github.com/angularsen/UnitsNet/issues/503 /// @@ -183,15 +198,13 @@ private class ValueUnit public override bool CanConvert(Type objectType) { if (IsNullable(objectType)) - { return CanConvertNullable(objectType); - } return objectType.Namespace != null && - (objectType.Namespace.Equals(nameof(UnitsNet)) || - objectType == typeof(ValueUnit) || - // All unit types implement IComparable - objectType == typeof(IComparable)); + (objectType.Namespace.Equals(nameof(UnitsNet)) || + objectType == typeof(ValueUnit) || + // All unit types implement IComparable + objectType == typeof(IComparable)); } /// diff --git a/UnitsNet.Tests/AssemblyAttributeTests.cs b/UnitsNet.Tests/AssemblyAttributeTests.cs index b48302b531..754846727d 100644 --- a/UnitsNet.Tests/AssemblyAttributeTests.cs +++ b/UnitsNet.Tests/AssemblyAttributeTests.cs @@ -11,25 +11,25 @@ namespace UnitsNet.Tests public class AssemblyAttributeTests { [Fact] - public static void AssemblyCopyrightShouldContain2013() + public static void AssemblyShouldBeClsCompliant() { var assembly = typeof(Length).GetTypeInfo().Assembly; - var copyrightAttribute = assembly - .CustomAttributes - .Single(x => x.AttributeType == typeof(AssemblyCopyrightAttribute)); - var copyrightString = copyrightAttribute.ConstructorArguments.Single().Value.ToString(); - var expectedYear = "2013"; - Assert.Contains(expectedYear, copyrightString); + var attributes = assembly.CustomAttributes.Select(x => x.AttributeType); + Assert.Contains(typeof(CLSCompliantAttribute), attributes); } [Fact] - public static void AssemblyShouldBeClsCompliant() + public static void AssemblyCopyrightShouldContain2013() { var assembly = typeof(Length).GetTypeInfo().Assembly; - var attributes = assembly.CustomAttributes.Select(x => x.AttributeType); - Assert.Contains(typeof(CLSCompliantAttribute), attributes); + var copyrightAttribute = assembly + .CustomAttributes + .Single(x => x.AttributeType == typeof(AssemblyCopyrightAttribute)); + string copyrightString = copyrightAttribute.ConstructorArguments.Single().Value.ToString(); + string expectedYear = "2013"; + Assert.Contains(expectedYear, copyrightString); } } } diff --git a/UnitsNet.Tests/AssertEx.cs b/UnitsNet.Tests/AssertEx.cs index aa82a72cc7..cf90732786 100644 --- a/UnitsNet.Tests/AssertEx.cs +++ b/UnitsNet.Tests/AssertEx.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; using Xunit; namespace UnitsNet.Tests @@ -13,21 +10,19 @@ public static class AssertEx { public static void EqualTolerance(double expected, double actual, double tolerance, ComparisonType comparisonType = ComparisonType.Relative) { - if (comparisonType == ComparisonType.Relative) + if(comparisonType == ComparisonType.Relative) { - var areEqual = Comparison.EqualsRelative(expected, actual, tolerance); + bool areEqual = Comparison.EqualsRelative(expected, actual, tolerance); - var difference = Math.Abs(expected - actual); - var relativeDifference = difference / expected; + double difference = Math.Abs(expected - actual); + double relativeDifference = difference / expected; - Assert.True(areEqual, - $"Values are not equal within relative tolerance: {tolerance:P4}\nExpected: {expected}\nActual: {actual}\nDiff: {relativeDifference:P4}"); + Assert.True( areEqual, $"Values are not equal within relative tolerance: {tolerance:P4}\nExpected: {expected}\nActual: {actual}\nDiff: {relativeDifference:P4}" ); } - else if (comparisonType == ComparisonType.Absolute) + else if( comparisonType == ComparisonType.Absolute ) { - var areEqual = Comparison.EqualsAbsolute(expected, actual, tolerance); - Assert.True(areEqual, - $"Values are not equal within absolute tolerance: {tolerance}\nExpected: {expected}\nActual: {actual}\nDiff: {actual - expected:e}"); + bool areEqual = Comparison.EqualsAbsolute(expected, actual, tolerance); + Assert.True( areEqual, $"Values are not equal within absolute tolerance: {tolerance}\nExpected: {expected}\nActual: {actual}\nDiff: {actual - expected:e}" ); } } } diff --git a/UnitsNet.Tests/BaseDimensionsTests.cs b/UnitsNet.Tests/BaseDimensionsTests.cs index a1ee6266e8..9c0b593590 100644 --- a/UnitsNet.Tests/BaseDimensionsTests.cs +++ b/UnitsNet.Tests/BaseDimensionsTests.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; using System.Collections.Generic; using Xunit; @@ -9,6 +6,20 @@ namespace UnitsNet.Tests { public class BaseDimensionsTests { + [Fact] + public void ConstructorImplementedCorrectly() + { + var baseDimensions = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + + Assert.True(baseDimensions.Length == 1); + Assert.True(baseDimensions.Mass == 2); + Assert.True(baseDimensions.Time == 3); + Assert.True(baseDimensions.Current == 4); + Assert.True(baseDimensions.Temperature == 5); + Assert.True(baseDimensions.Amount == 6); + Assert.True(baseDimensions.LuminousIntensity == 7); + } + [Theory] [InlineData(1, 0, 0, 0, 0, 0, 0)] [InlineData(0, 1, 0, 0, 0, 0, 0)] @@ -44,190 +55,135 @@ public void IsDerivedQuantityImplementedProperly(int length, int mass, int time, } [Fact] - public void AmountDimensionsDivideCorrectly() - { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 3, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 2, 0); - - var result = baseDimensions1.Divide(baseDimensions2); - - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 1); - Assert.True(result.LuminousIntensity == 0); - } - - [Fact] - public void AmountDimensionsDivideCorrectlyWithOperatorOverloads() + public void EqualsWorksAsExpected() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 3, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 2, 0); + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var result = baseDimensions1 / baseDimensions2; + Assert.True(baseDimensions1.Equals(baseDimensions2)); + Assert.True(baseDimensions2.Equals(baseDimensions1)); - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 1); - Assert.True(result.LuminousIntensity == 0); + Assert.False(baseDimensions1.Equals(null)); } [Fact] - public void AmountDimensionsMultiplyCorrectly() + public void EqualityOperatorsWorkAsExpected() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 6, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 7, 0); + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var result = baseDimensions1.Multiply(baseDimensions2); + Assert.True(baseDimensions1 == baseDimensions2); + Assert.True(baseDimensions2 == baseDimensions1); - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 13); - Assert.True(result.LuminousIntensity == 0); - } + Assert.False(baseDimensions1 == null); + Assert.False(null == baseDimensions1); - [Fact] - public void AmountDimensionsMultiplyCorrectlyWithOperatorOverloads() - { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 6, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 7, 0); + Assert.False(baseDimensions2 == null); + Assert.False(null == baseDimensions2); - var result = baseDimensions1 * baseDimensions2; + BaseDimensions nullBaseDimensions1 = null; + BaseDimensions nullBaseDimensions2 = null; - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 13); - Assert.True(result.LuminousIntensity == 0); + Assert.True(nullBaseDimensions1 == nullBaseDimensions2); } [Fact] - public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnInstanceProperty() + public void InequalityOperatorsWorkAsExpected() { - var length = Length.FromKilometers(100); - var duration = Duration.FromHours(1); + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(7, 6, 5, 4, 3, 2, 1); - var calculatedDimensions = length.Dimensions.Divide(duration.Dimensions); - Assert.True(calculatedDimensions == Speed.BaseDimensions); - } + Assert.True(baseDimensions1 != baseDimensions2); + Assert.True(baseDimensions2 != baseDimensions1); - [Fact] - public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnInstancePropertyWithOperatorOverloads() - { - var length = Length.FromKilometers(100); - var duration = Duration.FromHours(1); + Assert.True(baseDimensions1 != null); + Assert.True(null != baseDimensions1); - var calculatedDimensions = length.Dimensions / duration.Dimensions; - Assert.True(calculatedDimensions == Speed.BaseDimensions); - } + Assert.True(baseDimensions2 != null); + Assert.True(null != baseDimensions2); - [Fact] - public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnStaticProperty() - { - var calculatedDimensions = Length.BaseDimensions.Divide(Duration.BaseDimensions); - Assert.True(calculatedDimensions == Speed.BaseDimensions); - } + BaseDimensions nullBaseDimensions1 = null; + BaseDimensions nullBaseDimensions2 = null; - [Fact] - public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnStaticPropertyWithOperatorOverloads() - { - var calculatedDimensions = Length.BaseDimensions / Duration.BaseDimensions; - Assert.True(calculatedDimensions == Speed.BaseDimensions); + Assert.False(nullBaseDimensions1 != nullBaseDimensions2); } [Fact] - public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnInstanceProperty() + public void MultiplyThrowsExceptionIfPassedNull() { - var mass = Mass.FromPounds(205); - var acceleration = Acceleration.FromMetersPerSecondSquared(9.8); - - var calculatedDimensions = mass.Dimensions.Multiply(acceleration.Dimensions); - Assert.True(calculatedDimensions == Force.BaseDimensions); + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1.Multiply(null)); } [Fact] - public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnInstancePropertyWithOperatorOverloads() + public void DivideThrowsExceptionIfPassedNull() { - var mass = Mass.FromPounds(205); - var acceleration = Acceleration.FromMetersPerSecondSquared(9.8); - - var calculatedDimensions = mass.Dimensions * acceleration.Dimensions; - Assert.True(calculatedDimensions == Force.BaseDimensions); + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1.Divide(null)); } [Fact] - public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnStaticProperty() + public void MultiplyOperatorThrowsExceptionWithNull() { - var calculatedDimensions = Mass.BaseDimensions.Multiply(Acceleration.BaseDimensions); - Assert.True(calculatedDimensions == Force.BaseDimensions); + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1 / null); + Assert.Throws(() => null / baseDimensions1); } [Fact] - public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnStaticPropertyWithOperatorOverloads() + public void DivideOperatorThrowsExceptionWithNull() { - var calculatedDimensions = Mass.BaseDimensions * Acceleration.BaseDimensions; - Assert.True(calculatedDimensions == Force.BaseDimensions); + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + Assert.Throws(() => baseDimensions1 * null); + Assert.Throws(() => null * baseDimensions1); } [Fact] - public void CheckToStringUsingMolarEntropy() + public void LengthDimensionsMultiplyCorrectly() { - Assert.Equal("[Length]^2[Mass][Time]^-2[Temperature][Amount]", MolarEntropy.BaseDimensions.ToString()); - } + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - [Fact] - public void ConstructorImplementedCorrectly() - { - var baseDimensions = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var result = baseDimensions1.Multiply(baseDimensions2); - Assert.True(baseDimensions.Length == 1); - Assert.True(baseDimensions.Mass == 2); - Assert.True(baseDimensions.Time == 3); - Assert.True(baseDimensions.Current == 4); - Assert.True(baseDimensions.Temperature == 5); - Assert.True(baseDimensions.Amount == 6); - Assert.True(baseDimensions.LuminousIntensity == 7); + Assert.True(result.Length == 3); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void CurrentDimensionsDivideCorrectly() + public void MassDimensionsMultiplyCorrectly() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 2, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 3, 0, 0, 0, 0, 0); - var result = baseDimensions1.Divide(baseDimensions2); + var result = baseDimensions1.Multiply(baseDimensions2); Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); + Assert.True(result.Mass == 5); Assert.True(result.Time == 0); - Assert.True(result.Current == 1); + Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void CurrentDimensionsDivideCorrectlyWithOperatorOverloads() + public void TimeDimensionsMultiplyCorrectly() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 3, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 4, 0, 0, 0, 0); - var result = baseDimensions1 / baseDimensions2; + var result = baseDimensions1.Multiply(baseDimensions2); Assert.True(result.Length == 0); Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 1); + Assert.True(result.Time == 7); + Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); Assert.True(result.LuminousIntensity == 0); @@ -251,168 +207,228 @@ public void CurrentDimensionsMultiplyCorrectly() } [Fact] - public void CurrentDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void TemperatureDimensionsMultiplyCorrectly() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 5, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 6, 0, 0); - var result = baseDimensions1 * baseDimensions2; + var result = baseDimensions1.Multiply(baseDimensions2); Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); - Assert.True(result.Current == 9); - Assert.True(result.Temperature == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 11); Assert.True(result.Amount == 0); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void DimensionlessPropertyIsCorrect() + public void AmountDimensionsMultiplyCorrectly() { - Assert.True(BaseDimensions.Dimensionless == new BaseDimensions(0, 0, 0, 0, 0, 0, 0)); - } + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 6, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 7, 0); - [Fact] - public void DivideOperatorThrowsExceptionWithNull() - { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - Assert.Throws(() => baseDimensions1 * null); - Assert.Throws(() => null * baseDimensions1); + var result = baseDimensions1.Multiply(baseDimensions2); + + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 13); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void DivideThrowsExceptionIfPassedNull() + public void LuminousIntensityDimensionsMultiplyCorrectly() { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - Assert.Throws(() => baseDimensions1.Divide(null)); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 7); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 8); + + var result = baseDimensions1.Multiply(baseDimensions2); + + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 15); } [Fact] - public void EqualityOperatorsWorkAsExpected() + public void LengthDimensionsDivideCorrectly() { - var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions1 = new BaseDimensions(8, 0, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(7, 0, 0, 0, 0, 0, 0); - Assert.True(baseDimensions1 == baseDimensions2); - Assert.True(baseDimensions2 == baseDimensions1); + var result = baseDimensions1.Divide(baseDimensions2); - Assert.False(baseDimensions1 == null); - Assert.False(null == baseDimensions1); + Assert.True(result.Length == 1); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); + } - Assert.False(baseDimensions2 == null); - Assert.False(null == baseDimensions2); + [Fact] + public void MassDimensionsDivideCorrectly() + { + var baseDimensions1 = new BaseDimensions(0, 7, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 6, 0, 0, 0, 0, 0); - BaseDimensions nullBaseDimensions1 = null; - BaseDimensions nullBaseDimensions2 = null; + var result = baseDimensions1.Divide(baseDimensions2); - Assert.True(nullBaseDimensions1 == nullBaseDimensions2); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 1); + Assert.True(result.Time == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void EqualityWorksAsExpectedWithOperatorOverloads() + public void TimeDimensionsDivideCorrectly() { - var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions1 = new BaseDimensions(0, 0, 6, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 5, 0, 0, 0, 0); - Assert.True(baseDimensions1 == baseDimensions2); - Assert.True(baseDimensions2 == baseDimensions1); + var result = baseDimensions1.Divide(baseDimensions2); + + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 1); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void EqualsWorksAsExpected() + public void CurrentDimensionsDivideCorrectly() { - var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); - Assert.True(baseDimensions1.Equals(baseDimensions2)); - Assert.True(baseDimensions2.Equals(baseDimensions1)); + var result = baseDimensions1.Divide(baseDimensions2); - Assert.False(baseDimensions1.Equals(null)); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 0); + Assert.True(result.Current == 1); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void GetHashCodeWorksProperly() + public void TemperatureDimensionsDivideCorrectly() { - var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var baseDimensions2 = new BaseDimensions(7, 6, 5, 4, 3, 2, 1); - var baseDimensions3 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 4, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 3, 0, 0); - var hashSet = new HashSet(); + var result = baseDimensions1.Divide(baseDimensions2); - hashSet.Add(baseDimensions1); - Assert.Contains(baseDimensions1, hashSet); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 1); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 0); + } - hashSet.Add(baseDimensions2); - Assert.Contains(baseDimensions2, hashSet); + [Fact] + public void AmountDimensionsDivideCorrectly() + { + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 3, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 2, 0); - // Should be the same as baseDimensions1 - Assert.Contains(baseDimensions3, hashSet); + var result = baseDimensions1.Divide(baseDimensions2); - Assert.True(baseDimensions1.GetHashCode() != baseDimensions2.GetHashCode()); - Assert.True(baseDimensions1.GetHashCode() == baseDimensions3.GetHashCode()); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 1); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void InequalityOperatorsWorkAsExpected() + public void LuminousIntensityDimensionsDivideCorrectly() { - var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var baseDimensions2 = new BaseDimensions(7, 6, 5, 4, 3, 2, 1); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 2); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - Assert.True(baseDimensions1 != baseDimensions2); - Assert.True(baseDimensions2 != baseDimensions1); + var result = baseDimensions1.Divide(baseDimensions2); - Assert.True(baseDimensions1 != null); - Assert.True(null != baseDimensions1); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 0); + Assert.True(result.Current == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 0); + Assert.True(result.LuminousIntensity == 1); + } - Assert.True(baseDimensions2 != null); - Assert.True(null != baseDimensions2); + [Fact] + public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnStaticProperty() + { + var calculatedDimensions = Length.BaseDimensions.Divide(Duration.BaseDimensions); + Assert.True(calculatedDimensions == Speed.BaseDimensions); + } - BaseDimensions nullBaseDimensions1 = null; - BaseDimensions nullBaseDimensions2 = null; + [Fact] + public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnInstanceProperty() + { + var length = Length.FromKilometers(100); + var duration = Duration.FromHours(1); - Assert.False(nullBaseDimensions1 != nullBaseDimensions2); + var calculatedDimensions = length.Dimensions.Divide(duration.Dimensions); + Assert.True(calculatedDimensions == Speed.BaseDimensions); } [Fact] - public void IsDimensionlessMethodImplementedCorrectly() + public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnStaticProperty() { - Assert.True(BaseDimensions.Dimensionless.IsDimensionless()); - Assert.True(new BaseDimensions(0, 0, 0, 0, 0, 0, 0).IsDimensionless()); + var calculatedDimensions = Mass.BaseDimensions.Multiply(Acceleration.BaseDimensions); + Assert.True(calculatedDimensions == Force.BaseDimensions); + } - Assert.False(BaseDimensions.Dimensionless.IsBaseQuantity()); - Assert.False(BaseDimensions.Dimensionless.IsDerivedQuantity()); + [Fact] + public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnInstanceProperty() + { + var mass = Mass.FromPounds(205); + var acceleration = Acceleration.FromMetersPerSecondSquared(9.8); - // Example case - Assert.True(Level.BaseDimensions.IsDimensionless()); + var calculatedDimensions = mass.Dimensions.Multiply(acceleration.Dimensions); + Assert.True(calculatedDimensions == Force.BaseDimensions); } [Fact] - public void LengthDimensionsDivideCorrectly() + public void EqualityWorksAsExpectedWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(8, 0, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(7, 0, 0, 0, 0, 0, 0); - - var result = baseDimensions1.Divide(baseDimensions2); + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - Assert.True(result.Length == 1); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + Assert.True(baseDimensions1 == baseDimensions2); + Assert.True(baseDimensions2 == baseDimensions1); } [Fact] - public void LengthDimensionsDivideCorrectlyWithOperatorOverloads() + public void LengthDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(8, 0, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(7, 0, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - var result = baseDimensions1 / baseDimensions2; + var result = baseDimensions1 * baseDimensions2; - Assert.True(result.Length == 1); + Assert.True(result.Length == 3); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); @@ -422,15 +438,15 @@ public void LengthDimensionsDivideCorrectlyWithOperatorOverloads() } [Fact] - public void LengthDimensionsMultiplyCorrectly() + public void MassDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 2, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 3, 0, 0, 0, 0, 0); - var result = baseDimensions1.Multiply(baseDimensions2); + var result = baseDimensions1 * baseDimensions2; - Assert.True(result.Length == 3); - Assert.True(result.Mass == 0); + Assert.True(result.Length == 0); + Assert.True(result.Mass == 5); Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); @@ -439,16 +455,16 @@ public void LengthDimensionsMultiplyCorrectly() } [Fact] - public void LengthDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void TimeDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 3, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 4, 0, 0, 0, 0); var result = baseDimensions1 * baseDimensions2; - Assert.True(result.Length == 3); + Assert.True(result.Length == 0); Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); + Assert.True(result.Time == 7); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); @@ -456,54 +472,54 @@ public void LengthDimensionsMultiplyCorrectlyWithOperatorOverloads() } [Fact] - public void LuminousIntensityDimensionsDivideCorrectly() + public void CurrentDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 2); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); - var result = baseDimensions1.Divide(baseDimensions2); + var result = baseDimensions1 * baseDimensions2; Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); - Assert.True(result.Current == 0); + Assert.True(result.Current == 9); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 1); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void LuminousIntensityDimensionsDivideCorrectlyWithOperatorOverloads() + public void TemperatureDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 2); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 5, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 6, 0, 0); - var result = baseDimensions1 / baseDimensions2; + var result = baseDimensions1 * baseDimensions2; Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); + Assert.True(result.Temperature == 11); Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 1); + Assert.True(result.LuminousIntensity == 0); } [Fact] - public void LuminousIntensityDimensionsMultiplyCorrectly() + public void AmountDimensionsMultiplyCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 7); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 8); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 6, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 7, 0); - var result = baseDimensions1.Multiply(baseDimensions2); + var result = baseDimensions1 * baseDimensions2; Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 15); + Assert.True(result.Amount == 13); + Assert.True(result.LuminousIntensity == 0); } [Fact] @@ -524,15 +540,15 @@ public void LuminousIntensityDimensionsMultiplyCorrectlyWithOperatorOverloads() } [Fact] - public void MassDimensionsDivideCorrectly() + public void LengthDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 7, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 6, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(8, 0, 0, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(7, 0, 0, 0, 0, 0, 0); - var result = baseDimensions1.Divide(baseDimensions2); + var result = baseDimensions1 / baseDimensions2; - Assert.True(result.Length == 0); - Assert.True(result.Mass == 1); + Assert.True(result.Length == 1); + Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); @@ -558,16 +574,16 @@ public void MassDimensionsDivideCorrectlyWithOperatorOverloads() } [Fact] - public void MassDimensionsMultiplyCorrectly() + public void TimeDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 2, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 3, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 6, 0, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 5, 0, 0, 0, 0); - var result = baseDimensions1.Multiply(baseDimensions2); + var result = baseDimensions1 / baseDimensions2; Assert.True(result.Length == 0); - Assert.True(result.Mass == 5); - Assert.True(result.Time == 0); + Assert.True(result.Mass == 0); + Assert.True(result.Time == 1); Assert.True(result.Current == 0); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); @@ -575,44 +591,29 @@ public void MassDimensionsMultiplyCorrectly() } [Fact] - public void MassDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void CurrentDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 2, 0, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 3, 0, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 5, 0, 0, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 4, 0, 0, 0); - var result = baseDimensions1 * baseDimensions2; + var result = baseDimensions1 / baseDimensions2; Assert.True(result.Length == 0); - Assert.True(result.Mass == 5); + Assert.True(result.Mass == 0); Assert.True(result.Time == 0); - Assert.True(result.Current == 0); + Assert.True(result.Current == 1); Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void MultiplyOperatorThrowsExceptionWithNull() - { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - Assert.Throws(() => baseDimensions1 / null); - Assert.Throws(() => null / baseDimensions1); - } - - [Fact] - public void MultiplyThrowsExceptionIfPassedNull() - { - var baseDimensions1 = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - Assert.Throws(() => baseDimensions1.Multiply(null)); - } - - [Fact] - public void TemperatureDimensionsDivideCorrectly() + public void TemperatureDimensionsDivideCorrectlyWithOperatorOverloads() { var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 4, 0, 0); var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 3, 0, 0); - var result = baseDimensions1.Divide(baseDimensions2); + var result = baseDimensions1 / baseDimensions2; Assert.True(result.Length == 0); Assert.True(result.Mass == 0); @@ -624,10 +625,10 @@ public void TemperatureDimensionsDivideCorrectly() } [Fact] - public void TemperatureDimensionsDivideCorrectlyWithOperatorOverloads() + public void AmountDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 4, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 3, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 3, 0); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 2, 0); var result = baseDimensions1 / baseDimensions2; @@ -635,111 +636,107 @@ public void TemperatureDimensionsDivideCorrectlyWithOperatorOverloads() Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); - Assert.True(result.Temperature == 1); - Assert.True(result.Amount == 0); + Assert.True(result.Temperature == 0); + Assert.True(result.Amount == 1); Assert.True(result.LuminousIntensity == 0); } [Fact] - public void TemperatureDimensionsMultiplyCorrectly() + public void LuminousIntensityDimensionsDivideCorrectlyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 5, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 6, 0, 0); + var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 0, 0, 2); + var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - var result = baseDimensions1.Multiply(baseDimensions2); + var result = baseDimensions1 / baseDimensions2; Assert.True(result.Length == 0); Assert.True(result.Mass == 0); Assert.True(result.Time == 0); Assert.True(result.Current == 0); - Assert.True(result.Temperature == 11); + Assert.True(result.Temperature == 0); Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + Assert.True(result.LuminousIntensity == 1); } [Fact] - public void TemperatureDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnStaticPropertyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 0, 0, 5, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 0, 0, 6, 0, 0); - - var result = baseDimensions1 * baseDimensions2; - - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 0); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 11); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + var calculatedDimensions = Length.BaseDimensions / Duration.BaseDimensions; + Assert.True(calculatedDimensions == Speed.BaseDimensions); } [Fact] - public void TimeDimensionsDivideCorrectly() + public void CheckBaseDimensionDivisionWithSpeedEqualsDistanceDividedByTimeOnInstancePropertyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 6, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 5, 0, 0, 0, 0); + var length = Length.FromKilometers(100); + var duration = Duration.FromHours(1); - var result = baseDimensions1.Divide(baseDimensions2); + var calculatedDimensions = length.Dimensions / duration.Dimensions; + Assert.True(calculatedDimensions == Speed.BaseDimensions); + } - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 1); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + [Fact] + public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnStaticPropertyWithOperatorOverloads() + { + var calculatedDimensions = Mass.BaseDimensions * Acceleration.BaseDimensions; + Assert.True(calculatedDimensions == Force.BaseDimensions); } [Fact] - public void TimeDimensionsDivideCorrectlyWithOperatorOverloads() + public void CheckBaseDimensionMultiplicationWithForceEqualsMassTimesAccelerationOnInstancePropertyWithOperatorOverloads() { - var baseDimensions1 = new BaseDimensions(0, 0, 6, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 5, 0, 0, 0, 0); + var mass = Mass.FromPounds(205); + var acceleration = Acceleration.FromMetersPerSecondSquared(9.8); - var result = baseDimensions1 / baseDimensions2; + var calculatedDimensions = mass.Dimensions * acceleration.Dimensions; + Assert.True(calculatedDimensions == Force.BaseDimensions); + } - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 1); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + [Fact] + public void CheckToStringUsingMolarEntropy() + { + Assert.Equal("[Length]^2[Mass][Time]^-2[Temperature][Amount]", MolarEntropy.BaseDimensions.ToString()); } [Fact] - public void TimeDimensionsMultiplyCorrectly() + public void GetHashCodeWorksProperly() { - var baseDimensions1 = new BaseDimensions(0, 0, 3, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 4, 0, 0, 0, 0); + var baseDimensions1 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); + var baseDimensions2 = new BaseDimensions(7, 6, 5, 4, 3, 2, 1); + var baseDimensions3 = new BaseDimensions(1, 2, 3, 4, 5, 6, 7); - var result = baseDimensions1.Multiply(baseDimensions2); + var hashSet = new HashSet(); - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 7); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + hashSet.Add(baseDimensions1); + Assert.Contains(baseDimensions1, hashSet); + + hashSet.Add(baseDimensions2); + Assert.Contains(baseDimensions2, hashSet); + + // Should be the same as baseDimensions1 + Assert.Contains(baseDimensions3, hashSet); + + Assert.True(baseDimensions1.GetHashCode() != baseDimensions2.GetHashCode()); + Assert.True(baseDimensions1.GetHashCode() == baseDimensions3.GetHashCode()); } [Fact] - public void TimeDimensionsMultiplyCorrectlyWithOperatorOverloads() + public void DimensionlessPropertyIsCorrect() { - var baseDimensions1 = new BaseDimensions(0, 0, 3, 0, 0, 0, 0); - var baseDimensions2 = new BaseDimensions(0, 0, 4, 0, 0, 0, 0); + Assert.True(BaseDimensions.Dimensionless == new BaseDimensions(0, 0, 0, 0, 0, 0, 0)); + } - var result = baseDimensions1 * baseDimensions2; + [Fact] + public void IsDimensionlessMethodImplementedCorrectly() + { + Assert.True(BaseDimensions.Dimensionless.IsDimensionless()); + Assert.True(new BaseDimensions(0, 0, 0, 0, 0, 0, 0).IsDimensionless()); - Assert.True(result.Length == 0); - Assert.True(result.Mass == 0); - Assert.True(result.Time == 7); - Assert.True(result.Current == 0); - Assert.True(result.Temperature == 0); - Assert.True(result.Amount == 0); - Assert.True(result.LuminousIntensity == 0); + Assert.False(BaseDimensions.Dimensionless.IsBaseQuantity()); + Assert.False(BaseDimensions.Dimensionless.IsDerivedQuantity()); + + // Example case + Assert.True(Level.BaseDimensions.IsDimensionless()); } } } diff --git a/UnitsNet.Tests/BaseUnitsTests.cs b/UnitsNet.Tests/BaseUnitsTests.cs index d34da832ea..3954e61b93 100644 --- a/UnitsNet.Tests/BaseUnitsTests.cs +++ b/UnitsNet.Tests/BaseUnitsTests.cs @@ -9,13 +9,13 @@ namespace UnitsNet.Tests { public class BaseUnitsTests { - private static readonly BaseUnits siBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + private static BaseUnits siBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - private static readonly BaseUnits siBaseUnitsCopy = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + private static BaseUnits siBaseUnitsCopy = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - private static readonly BaseUnits nonSiBaseUnits = new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, + private static BaseUnits nonSiBaseUnits = new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); [Fact] @@ -34,21 +34,13 @@ public void ConstructorSetsUnitsProperly() } [Fact] - public void EqualityOperatorIsImplementedCorrectly() + public void EqualsObjectIsImplementedCorrectly() { - Assert.True(siBaseUnits == siBaseUnitsCopy); - Assert.True(siBaseUnitsCopy == siBaseUnits); - - Assert.False(siBaseUnits == nonSiBaseUnits); - Assert.False(nonSiBaseUnits == siBaseUnits); - - Assert.False(siBaseUnits == null); - Assert.False(null == siBaseUnits); - - BaseUnits nullBaseUnits1 = null; - BaseUnits nullBaseUnits2 = null; + Assert.True(siBaseUnits.Equals((object)siBaseUnitsCopy)); + Assert.False(siBaseUnits.Equals((object)nonSiBaseUnits)); - Assert.True(nullBaseUnits1 == nullBaseUnits2); + Assert.False(siBaseUnits.Equals("Some object.")); + Assert.False(siBaseUnits.Equals((IFormatProvider)null)); } [Fact] @@ -64,26 +56,21 @@ public void EqualsBaseUnitsIsImplementedCorrectly() } [Fact] - public void EqualsObjectIsImplementedCorrectly() + public void EqualityOperatorIsImplementedCorrectly() { - Assert.True(siBaseUnits.Equals((object) siBaseUnitsCopy)); - Assert.False(siBaseUnits.Equals((object) nonSiBaseUnits)); + Assert.True(siBaseUnits == siBaseUnitsCopy); + Assert.True(siBaseUnitsCopy == siBaseUnits); - Assert.False(siBaseUnits.Equals("Some object.")); - Assert.False(siBaseUnits.Equals((IFormatProvider) null)); - } + Assert.False(siBaseUnits == nonSiBaseUnits); + Assert.False(nonSiBaseUnits == siBaseUnits); - [Fact] - public void ExistsInWorksCorrectly() - { - Assert.False(BaseUnits.Undefined.IsSubsetOf(siBaseUnits)); - Assert.False(siBaseUnits.IsSubsetOf(BaseUnits.Undefined)); + Assert.False(siBaseUnits == null); + Assert.False(null == siBaseUnits); - var meterBaseUnits = new BaseUnits(LengthUnit.Meter); - Assert.True(meterBaseUnits.IsSubsetOf(siBaseUnits)); + BaseUnits nullBaseUnits1 = null; + BaseUnits nullBaseUnits2 = null; - // Not all units in siBaseUnits will exist in meterBaseUnits - Assert.False(siBaseUnits.IsSubsetOf(meterBaseUnits)); + Assert.True(nullBaseUnits1 == nullBaseUnits2); } [Fact] @@ -105,43 +92,21 @@ public void InequalityOperatorIsImplementedCorrectly() } [Fact] - public void IsFullyDefined_FalseIfAnyBaseUnitIsUndefined() + public void UndefinedHasAllBaseUnitsAsUndefined() { - Assert.False(new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, - current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(LengthUnit.Meter, time: DurationUnit.Second, - current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, - current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, amount: AmountOfSubstanceUnit.Mole, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, - luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); - - Assert.False(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole - ).IsFullyDefined); + Assert.Equal(LengthUnit.Undefined, BaseUnits.Undefined.Length); + Assert.Equal(MassUnit.Undefined, BaseUnits.Undefined.Mass); + Assert.Equal(DurationUnit.Undefined, BaseUnits.Undefined.Time); + Assert.Equal(ElectricCurrentUnit.Undefined, BaseUnits.Undefined.Current); + Assert.Equal(TemperatureUnit.Undefined, BaseUnits.Undefined.Temperature); + Assert.Equal(AmountOfSubstanceUnit.Undefined, BaseUnits.Undefined.Amount); + Assert.Equal(LuminousIntensityUnit.Undefined, BaseUnits.Undefined.LuminousIntensity); } [Fact] - public void IsFullyDefined_TrueIfAllBaseUnitDefined() + public void UndefinedIsSubsetOfUndefined() { - Assert.True(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, - LuminousIntensityUnit.Candela).IsFullyDefined); + Assert.True(BaseUnits.Undefined.IsSubsetOf(BaseUnits.Undefined)); } [Fact] @@ -150,6 +115,19 @@ public void IsSubsetOfReturnsFalseWithNull() Assert.False(siBaseUnits.IsSubsetOf(null)); } + [Fact] + public void ExistsInWorksCorrectly() + { + Assert.False(BaseUnits.Undefined.IsSubsetOf(siBaseUnits)); + Assert.False(siBaseUnits.IsSubsetOf(BaseUnits.Undefined)); + + var meterBaseUnits = new BaseUnits(LengthUnit.Meter); + Assert.True(meterBaseUnits.IsSubsetOf(siBaseUnits)); + + // Not all units in siBaseUnits will exist in meterBaseUnits + Assert.False(siBaseUnits.IsSubsetOf(meterBaseUnits)); + } + [Fact] public void ToStringGivesExpectedResult() { @@ -160,21 +138,43 @@ public void ToStringGivesExpectedResult() } [Fact] - public void UndefinedHasAllBaseUnitsAsUndefined() + public void IsFullyDefined_TrueIfAllBaseUnitDefined() { - Assert.Equal(LengthUnit.Undefined, BaseUnits.Undefined.Length); - Assert.Equal(MassUnit.Undefined, BaseUnits.Undefined.Mass); - Assert.Equal(DurationUnit.Undefined, BaseUnits.Undefined.Time); - Assert.Equal(ElectricCurrentUnit.Undefined, BaseUnits.Undefined.Current); - Assert.Equal(TemperatureUnit.Undefined, BaseUnits.Undefined.Temperature); - Assert.Equal(AmountOfSubstanceUnit.Undefined, BaseUnits.Undefined.Amount); - Assert.Equal(LuminousIntensityUnit.Undefined, BaseUnits.Undefined.LuminousIntensity); + Assert.True(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, + LuminousIntensityUnit.Candela).IsFullyDefined); } - + [Fact] - public void UndefinedIsSubsetOfUndefined() + public void IsFullyDefined_FalseIfAnyBaseUnitIsUndefined() { - Assert.True(BaseUnits.Undefined.IsSubsetOf(BaseUnits.Undefined)); + Assert.False(new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, + current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, + current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, + current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, + temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, + current: ElectricCurrentUnit.Ampere, amount: AmountOfSubstanceUnit.Mole, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, + current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, + luminousIntensity: LuminousIntensityUnit.Candela).IsFullyDefined); + + Assert.False(new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, + current: ElectricCurrentUnit.Ampere, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole + ).IsFullyDefined); } } } diff --git a/UnitsNet.Tests/CustomCode/AccelerationTests.cs b/UnitsNet.Tests/CustomCode/AccelerationTests.cs index b80b0936f6..30d4aafca0 100644 --- a/UnitsNet.Tests/CustomCode/AccelerationTests.cs +++ b/UnitsNet.Tests/CustomCode/AccelerationTests.cs @@ -36,7 +36,7 @@ public class AccelerationTests : AccelerationTestsBase [Fact] public void AccelerationTimesDensityEqualsSpecificWeight() { - var specificWeight = Acceleration.FromMetersPerSecondSquared(10) * Density.FromKilogramsPerCubicMeter(2); + SpecificWeight specificWeight = Acceleration.FromMetersPerSecondSquared(10) * Density.FromKilogramsPerCubicMeter(2); Assert.Equal(SpecificWeight.FromNewtonsPerCubicMeter(20), specificWeight); } } diff --git a/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs b/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs index aa140c3be1..e51ce88b3c 100644 --- a/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs @@ -18,13 +18,13 @@ public class AmplitudeRatioTests : AmplitudeRatioTestsBase protected override void AssertLogarithmicAddition() { - var v = AmplitudeRatio.FromDecibelVolts(40); + AmplitudeRatio v = AmplitudeRatio.FromDecibelVolts(40); AssertEx.EqualTolerance(46.0205999133, (v + v).DecibelVolts, DecibelVoltsTolerance); } protected override void AssertLogarithmicSubtraction() { - var v = AmplitudeRatio.FromDecibelVolts(40); + AmplitudeRatio v = AmplitudeRatio.FromDecibelVolts(40); AssertEx.EqualTolerance(46.6982292275, (AmplitudeRatio.FromDecibelVolts(50) - v).DecibelVolts, DecibelVoltsTolerance); } @@ -34,7 +34,7 @@ protected override void AssertLogarithmicSubtraction() [InlineData(-10)] public void InvalidVoltage_ExpectArgumentOutOfRangeException(double voltage) { - var invalidVoltage = ElectricPotential.FromVolts(voltage); + ElectricPotential invalidVoltage = ElectricPotential.FromVolts(voltage); // ReSharper disable once ObjectCreationAsStatement Assert.Throws(() => new AmplitudeRatio(invalidVoltage)); @@ -48,9 +48,9 @@ public void InvalidVoltage_ExpectArgumentOutOfRangeException(double voltage) public void ExpectVoltageConvertedToAmplitudeRatioCorrectly(double voltage, double expected) { // Amplitude ratio increases linearly by 20 dBV with power-of-10 increases of voltage. - var v = ElectricPotential.FromVolts(voltage); + ElectricPotential v = ElectricPotential.FromVolts(voltage); - var actual = AmplitudeRatio.FromElectricPotential(v).DecibelVolts; + double actual = AmplitudeRatio.FromElectricPotential(v).DecibelVolts; Assert.Equal(expected, actual); } @@ -63,9 +63,9 @@ public void ExpectVoltageConvertedToAmplitudeRatioCorrectly(double voltage, doub public void ExpectAmplitudeRatioConvertedToVoltageCorrectly(double amplitudeRatio, double expected) { // Voltage increases by powers of 10 for every 20 dBV increase in amplitude ratio. - var ar = AmplitudeRatio.FromDecibelVolts(amplitudeRatio); + AmplitudeRatio ar = AmplitudeRatio.FromDecibelVolts(amplitudeRatio); - var actual = ar.ToElectricPotential().Volts; + double actual = ar.ToElectricPotential().Volts; Assert.Equal(expected, actual); } @@ -78,9 +78,9 @@ public void ExpectAmplitudeRatioConvertedToVoltageCorrectly(double amplitudeRati [InlineData(60, 13.01)] public void AmplitudeRatioToPowerRatio_50OhmImpedance(double dBmV, double expected) { - var ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); + AmplitudeRatio ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); - var actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(50)).DecibelMilliwatts, 2); + double actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(50)).DecibelMilliwatts, 2); Assert.Equal(expected, actual); } @@ -91,9 +91,9 @@ public void AmplitudeRatioToPowerRatio_50OhmImpedance(double dBmV, double expect [InlineData(60, 11.25)] public void AmplitudeRatioToPowerRatio_75OhmImpedance(double dBmV, double expected) { - var ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); + AmplitudeRatio ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); - var actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(75)).DecibelMilliwatts, 2); + double actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(75)).DecibelMilliwatts, 2); Assert.Equal(expected, actual); } } diff --git a/UnitsNet.Tests/CustomCode/AngleTests.cs b/UnitsNet.Tests/CustomCode/AngleTests.cs index b9b853e170..1641165cce 100644 --- a/UnitsNet.Tests/CustomCode/AngleTests.cs +++ b/UnitsNet.Tests/CustomCode/AngleTests.cs @@ -39,14 +39,14 @@ public class AngleTests : AngleTestsBase [Fact] public void AngleDividedByDurationEqualsRotationalSpeed() { - var rotationalSpeed = Angle.FromRadians(10) / Duration.FromSeconds(5); + RotationalSpeed rotationalSpeed = Angle.FromRadians(10) / Duration.FromSeconds(5); Assert.Equal(rotationalSpeed, RotationalSpeed.FromRadiansPerSecond(2)); } [Fact] public void AngleDividedByTimeSpanEqualsRotationalSpeed() { - var rotationalSpeed = Angle.FromRadians(10) / TimeSpan.FromSeconds(5); + RotationalSpeed rotationalSpeed = Angle.FromRadians(10) / TimeSpan.FromSeconds(5); Assert.Equal(rotationalSpeed, RotationalSpeed.FromRadiansPerSecond(2)); } } diff --git a/UnitsNet.Tests/CustomCode/AreaTests.cs b/UnitsNet.Tests/CustomCode/AreaTests.cs index bfefa947a1..d637cd18a9 100644 --- a/UnitsNet.Tests/CustomCode/AreaTests.cs +++ b/UnitsNet.Tests/CustomCode/AreaTests.cs @@ -8,11 +8,12 @@ namespace UnitsNet.Tests.CustomCode { public class AreaTests : AreaTestsBase { + protected override double SquareKilometersInOneSquareMeter => 1E-6; protected override double SquareMetersInOneSquareMeter => 1; - protected override double AcresInOneSquareMeter => 2.471053816137 * 1E-4; + protected override double AcresInOneSquareMeter => 2.471053816137*1E-4; protected override double HectaresInOneSquareMeter => 1E-4; @@ -28,7 +29,7 @@ public class AreaTests : AreaTestsBase protected override double SquareInchesInOneSquareMeter => 1550.003100; - protected override double SquareMilesInOneSquareMeter => 3.86102 * 1E-7; + protected override double SquareMilesInOneSquareMeter => 3.86102*1E-7; protected override double SquareYardsInOneSquareMeter => 1.19599; @@ -36,6 +37,20 @@ public class AreaTests : AreaTestsBase protected override double SquareNauticalMilesInOneSquareMeter => 0.00000029155335; + [Fact] + public void AreaDividedByLengthEqualsLength() + { + Length length = Area.FromSquareMeters(50)/Length.FromMeters(5); + Assert.Equal(length, Length.FromMeters(10)); + } + + [Fact] + public void AreaTimesMassFluxEqualsMassFlow() + { + MassFlow massFlow = Area.FromSquareMeters(20) * MassFlux.FromKilogramsPerSecondPerSquareMeter(2); + Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(40)); + } + [Theory] [InlineData(0, 0)] [InlineData(0.5, 0.19634954084936208)] @@ -43,9 +58,9 @@ public class AreaTests : AreaTestsBase [InlineData(2, 3.141592653589793)] public void AreaFromCicleDiameterCalculatedCorrectly(double diameterMeters, double expected) { - var diameter = Length.FromMeters(diameterMeters); + Length diameter = Length.FromMeters(diameterMeters); - var actual = Area.FromCircleDiameter(diameter).SquareMeters; + double actual = Area.FromCircleDiameter(diameter).SquareMeters; Assert.Equal(expected, actual); } @@ -57,32 +72,25 @@ public void AreaFromCicleDiameterCalculatedCorrectly(double diameterMeters, doub [InlineData(2, 12.566370614359173)] public void AreaFromCicleRadiusCalculatedCorrectly(double radiusMeters, double expected) { - var radius = Length.FromMeters(radiusMeters); + Length radius = Length.FromMeters(radiusMeters); - var actual = Area.FromCircleRadius(radius).SquareMeters; + double actual = Area.FromCircleRadius(radius).SquareMeters; Assert.Equal(expected, actual); } [Fact] - public void AreaDividedByLengthEqualsLength() - { - var length = Area.FromSquareMeters(50) / Length.FromMeters(5); - Assert.Equal(length, Length.FromMeters(10)); - } - - [Fact] - public void AreaTimesMassFluxEqualsMassFlow() + public void AreaTimesSpeedEqualsVolumeFlow() { - var massFlow = Area.FromSquareMeters(20) * MassFlux.FromKilogramsPerSecondPerSquareMeter(2); - Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(40)); + VolumeFlow volumeFlow = Area.FromSquareMeters(20) * Speed.FromMetersPerSecond(2); + Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(40), volumeFlow); } [Fact] - public void AreaTimesSpeedEqualsVolumeFlow() + public void Constructor_UnitSystemSI_AssignsSIUnit() { - var volumeFlow = Area.FromSquareMeters(20) * Speed.FromMetersPerSecond(2); - Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(40), volumeFlow); + var area = new Area(1.0, UnitSystem.SI); + Assert.Equal(AreaUnit.SquareMeter, area.Unit); } [Fact] @@ -92,13 +100,6 @@ public void As_GivenSIUnitSystem_ReturnsSIValue() Assert.Equal(0.00129032, squareInches.As(UnitSystem.SI)); } - [Fact] - public void Constructor_UnitSystemSI_AssignsSIUnit() - { - var area = new Area(1.0, UnitSystem.SI); - Assert.Equal(AreaUnit.SquareMeter, area.Unit); - } - [Fact] public void ToUnit_GivenSIUnitSystem_ReturnsSIQuantity() { diff --git a/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs b/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs index 6e649a4824..ed637226a8 100644 --- a/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs +++ b/UnitsNet.Tests/CustomCode/BrakeSpecificFuelConsumptionTests.cs @@ -1,6 +1,7 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using Xunit; namespace UnitsNet.Tests.CustomCode @@ -14,24 +15,24 @@ public class BrakeSpecificFuelConsumptionTests : BrakeSpecificFuelConsumptionTes protected override double PoundsPerMechanicalHorsepowerHourInOneKilogramPerJoule => 5918352.5016; [Fact] - public void BrakeSpecificFuelConsumptionTimesSpecificEnergyEqualsEnergy() + public void PowerTimesBrakeSpecificFuelConsumptionEqualsMassFlow() { - var value = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); - Assert.Equal(200.0, value); + MassFlow massFlow = BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0) * Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0); + AssertEx.EqualTolerance(20.0, massFlow.TonnesPerDay, 1e-11); } [Fact] public void DoubleDividedByBrakeSpecificFuelConsumptionEqualsSpecificEnergy() { - var massFlow = 2.0 / BrakeSpecificFuelConsumption.FromKilogramsPerJoule(4.0); + SpecificEnergy massFlow = 2.0 / BrakeSpecificFuelConsumption.FromKilogramsPerJoule(4.0); Assert.Equal(SpecificEnergy.FromJoulesPerKilogram(0.5), massFlow); } [Fact] - public void PowerTimesBrakeSpecificFuelConsumptionEqualsMassFlow() + public void BrakeSpecificFuelConsumptionTimesSpecificEnergyEqualsEnergy() { - var massFlow = BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0) * Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0); - AssertEx.EqualTolerance(20.0, massFlow.TonnesPerDay, 1e-11); + double value = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); + Assert.Equal(200.0, value); } } } diff --git a/UnitsNet.Tests/CustomCode/DensityTests.cs b/UnitsNet.Tests/CustomCode/DensityTests.cs index 796da4ad9e..6d70e059c2 100644 --- a/UnitsNet.Tests/CustomCode/DensityTests.cs +++ b/UnitsNet.Tests/CustomCode/DensityTests.cs @@ -88,38 +88,38 @@ public class DensityTests : DensityTestsBase protected override double KilogramsPerLiterInOneKilogramPerCubicMeter => 1e-3; [Fact] - public void DensityTimesAccelerationEqualsSpecificWeight() + public static void DensityTimesVolumeEqualsMass() { - var specificWeight = Density.FromKilogramsPerCubicMeter(10) * Acceleration.FromMetersPerSecondSquared(2); - Assert.Equal(SpecificWeight.FromNewtonsPerCubicMeter(20), specificWeight); + Mass mass = Density.FromKilogramsPerCubicMeter(2) * Volume.FromCubicMeters(3); + Assert.Equal(mass, Mass.FromKilograms(6)); } [Fact] - public static void DensityTimesKinematicViscosityEqualsDynamicViscosity() + public static void VolumeTimesDensityEqualsMass() { - var dynamicViscosity = Density.FromKilogramsPerCubicMeter(2) * KinematicViscosity.FromSquareMetersPerSecond(10); - Assert.Equal(dynamicViscosity, DynamicViscosity.FromNewtonSecondsPerMeterSquared(20)); + Mass mass = Volume.FromCubicMeters(3) * Density.FromKilogramsPerCubicMeter(2); + Assert.Equal(mass, Mass.FromKilograms(6)); } [Fact] - public void DensityTimesSpeedEqualsMassFlux() + public static void DensityTimesKinematicViscosityEqualsDynamicViscosity() { - var massFlux = Density.FromKilogramsPerCubicMeter(20) * Speed.FromMetersPerSecond(2); - Assert.Equal(massFlux, MassFlux.FromKilogramsPerSecondPerSquareMeter(40)); + DynamicViscosity dynamicViscosity = Density.FromKilogramsPerCubicMeter(2) * KinematicViscosity.FromSquareMetersPerSecond(10); + Assert.Equal(dynamicViscosity, DynamicViscosity.FromNewtonSecondsPerMeterSquared(20)); } - + [Fact] - public static void DensityTimesVolumeEqualsMass() + public void DensityTimesSpeedEqualsMassFlux() { - var mass = Density.FromKilogramsPerCubicMeter(2) * Volume.FromCubicMeters(3); - Assert.Equal(mass, Mass.FromKilograms(6)); + MassFlux massFlux = Density.FromKilogramsPerCubicMeter(20) * Speed.FromMetersPerSecond(2); + Assert.Equal(massFlux, MassFlux.FromKilogramsPerSecondPerSquareMeter(40)); } [Fact] - public static void VolumeTimesDensityEqualsMass() + public void DensityTimesAccelerationEqualsSpecificWeight() { - var mass = Volume.FromCubicMeters(3) * Density.FromKilogramsPerCubicMeter(2); - Assert.Equal(mass, Mass.FromKilograms(6)); + SpecificWeight specificWeight = Density.FromKilogramsPerCubicMeter(10) * Acceleration.FromMetersPerSecondSquared(2); + Assert.Equal(SpecificWeight.FromNewtonsPerCubicMeter(20), specificWeight); } } } diff --git a/UnitsNet.Tests/CustomCode/DurationTests.cs b/UnitsNet.Tests/CustomCode/DurationTests.cs index d150a76d45..4facb8eab1 100644 --- a/UnitsNet.Tests/CustomCode/DurationTests.cs +++ b/UnitsNet.Tests/CustomCode/DurationTests.cs @@ -1,9 +1,9 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using Xunit; using System; using System.Globalization; -using Xunit; namespace UnitsNet.Tests.CustomCode { @@ -29,157 +29,157 @@ public class DurationTests : DurationTestsBase protected override double Years365InOneSecond => 3.170979198376458e-8; - [Theory] - [InlineData("1s", 1)] - [InlineData("2 seconds", 2)] - [InlineData("1 ms", 1e-3)] - [InlineData("1000 msec", 1)] - [InlineData("1 с", 1, "ru-RU")] - [InlineData("1 сек", 1, "ru-RU")] - [InlineData("1000 мс", 1, "ru-RU")] - [InlineData("1000 мсек", 1, "ru-RU")] - public void DurationFromStringUsingMultipleAbbreviationsParsedCorrectly(string textValue, double expectedSeconds, string culture = null) + [Fact] + public static void ToTimeSpanShouldThrowExceptionOnValuesLargerThanTimeSpanMax() { - var cultureInfo = culture == null ? null : new CultureInfo(culture); - - AssertEx.EqualTolerance(expectedSeconds, Duration.Parse(textValue, cultureInfo).Seconds, SecondsTolerance); + Duration duration = Duration.FromSeconds(TimeSpan.MaxValue.TotalSeconds + 1); + Assert.Throws(() => duration.ToTimeSpan()); } [Fact] - public static void DateTimeMinusDurationReturnsDateTime() + public static void ToTimeSpanShouldThrowExceptionOnValuesSmallerThanTimeSpanMin() { - var dateTime = new DateTime(2016, 1, 2); - var oneDay = Duration.FromDays(1); - var result = dateTime - oneDay; - var expected = new DateTime(2016, 1, 1); - Assert.Equal(expected, result); + Duration duration = Duration.FromSeconds(TimeSpan.MinValue.TotalSeconds - 1); + Assert.Throws(() => duration.ToTimeSpan()); } [Fact] - public static void DateTimePlusDurationReturnsDateTime() + public static void ToTimeSpanShouldNotThrowExceptionOnValuesSlightlyLargerThanTimeSpanMin() { - var dateTime = new DateTime(2016, 1, 1); - var oneDay = Duration.FromDays(1); - var result = dateTime + oneDay; - var expected = new DateTime(2016, 1, 2); - Assert.Equal(expected, result); + Duration duration = Duration.FromSeconds(TimeSpan.MinValue.TotalSeconds + 1); + TimeSpan timeSpan = duration.ToTimeSpan(); + AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-3); } [Fact] - public static void DurationGreaterThanOrEqualTimeSpanShouldReturnCorrectly() + public static void ToTimeSpanShouldNotThrowExceptionOnValuesSlightlySmallerThanTimeSpanMax() { - var timeSpan = TimeSpan.FromHours(11); - var duration = Duration.FromHours(12); - Assert.True(duration >= timeSpan, "duration should be greater than timeSpan"); + Duration duration = Duration.FromSeconds(TimeSpan.MaxValue.TotalSeconds - 1); + TimeSpan timeSpan = duration.ToTimeSpan(); + AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-3); } [Fact] - public static void DurationGreaterThanTimeSpanShouldReturnCorrectly() + public static void ExplicitCastToTimeSpanShouldReturnSameValue() { - var timeSpan = TimeSpan.FromHours(11); - var duration = Duration.FromHours(12); - Assert.True(duration > timeSpan, "duration should be greater than timeSpan"); + Duration duration = Duration.FromSeconds(60); + TimeSpan timeSpan = (TimeSpan)duration; + AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-10); } [Fact] - public static void DurationLessThanOrEqualTimeSpanShouldReturnCorrectly() + public static void ExplicitCastToDurationShouldReturnSameValue() { - var timeSpan = TimeSpan.FromHours(11); - var duration = Duration.FromHours(10); - Assert.True(duration <= timeSpan, "duration should be less than timeSpan"); + TimeSpan timeSpan = TimeSpan.FromSeconds(60); + Duration duration = (Duration)timeSpan; + AssertEx.EqualTolerance(timeSpan.TotalSeconds, duration.Seconds, 1e-10); } [Fact] - public static void DurationLessThanTimeSpanShouldReturnCorrectly() + public static void DateTimePlusDurationReturnsDateTime() { - var timeSpan = TimeSpan.FromHours(11); - var duration = Duration.FromHours(10); - Assert.True(duration < timeSpan, "duration should be less than timeSpan"); + DateTime dateTime = new DateTime(2016, 1, 1); + Duration oneDay = Duration.FromDays(1); + DateTime result = dateTime + oneDay; + DateTime expected = new DateTime(2016, 1, 2); + Assert.Equal(expected, result); } [Fact] - public void DurationTimesVolumeFlowEqualsVolume() + public static void DateTimeMinusDurationReturnsDateTime() { - var volume = Duration.FromSeconds(20) * VolumeFlow.FromCubicMetersPerSecond(2); - Assert.Equal(Volume.FromCubicMeters(40), volume); + DateTime dateTime = new DateTime(2016, 1, 2); + Duration oneDay = Duration.FromDays(1); + DateTime result = dateTime - oneDay; + DateTime expected = new DateTime(2016, 1, 1); + Assert.Equal(expected, result); } [Fact] - public static void ExplicitCastToDurationShouldReturnSameValue() + public static void TimeSpanLessThanDurationShouldReturnCorrectly() { - var timeSpan = TimeSpan.FromSeconds(60); - var duration = (Duration) timeSpan; - AssertEx.EqualTolerance(timeSpan.TotalSeconds, duration.Seconds, 1e-10); + TimeSpan timeSpan = TimeSpan.FromHours(10); + Duration duration = Duration.FromHours(11); + Assert.True(timeSpan < duration, "timeSpan should be less than duration"); } [Fact] - public static void ExplicitCastToTimeSpanShouldReturnSameValue() + public static void TimeSpanGreaterThanDurationShouldReturnCorrectly() { - var duration = Duration.FromSeconds(60); - var timeSpan = (TimeSpan) duration; - AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-10); + TimeSpan timeSpan = TimeSpan.FromHours(12); + Duration duration = Duration.FromHours(11); + Assert.True(timeSpan > duration, "timeSpan should be greater than duration"); } [Fact] - public static void TimeSpanGreaterThanDurationShouldReturnCorrectly() + public static void DurationLessThanTimeSpanShouldReturnCorrectly() { - var timeSpan = TimeSpan.FromHours(12); - var duration = Duration.FromHours(11); - Assert.True(timeSpan > duration, "timeSpan should be greater than duration"); + TimeSpan timeSpan = TimeSpan.FromHours(11); + Duration duration = Duration.FromHours(10); + Assert.True(duration < timeSpan, "duration should be less than timeSpan"); } [Fact] - public static void TimeSpanGreaterThanOrEqualDurationShouldReturnCorrectly() + public static void DurationGreaterThanTimeSpanShouldReturnCorrectly() { - var timeSpan = TimeSpan.FromHours(12); - var duration = Duration.FromHours(11); - Assert.True(timeSpan >= duration, "timeSpan should be greater than duration"); + TimeSpan timeSpan = TimeSpan.FromHours(11); + Duration duration = Duration.FromHours(12); + Assert.True(duration > timeSpan, "duration should be greater than timeSpan"); } [Fact] public static void TimeSpanLessOrEqualThanDurationShouldReturnCorrectly() { - var timeSpan = TimeSpan.FromHours(10); - var duration = Duration.FromHours(11); + TimeSpan timeSpan = TimeSpan.FromHours(10); + Duration duration = Duration.FromHours(11); Assert.True(timeSpan <= duration, "timeSpan should be less than duration"); } [Fact] - public static void TimeSpanLessThanDurationShouldReturnCorrectly() + public static void TimeSpanGreaterThanOrEqualDurationShouldReturnCorrectly() { - var timeSpan = TimeSpan.FromHours(10); - var duration = Duration.FromHours(11); - Assert.True(timeSpan < duration, "timeSpan should be less than duration"); + TimeSpan timeSpan = TimeSpan.FromHours(12); + Duration duration = Duration.FromHours(11); + Assert.True(timeSpan >= duration, "timeSpan should be greater than duration"); } [Fact] - public static void ToTimeSpanShouldNotThrowExceptionOnValuesSlightlyLargerThanTimeSpanMin() + public static void DurationLessThanOrEqualTimeSpanShouldReturnCorrectly() { - var duration = Duration.FromSeconds(TimeSpan.MinValue.TotalSeconds + 1); - var timeSpan = duration.ToTimeSpan(); - AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-3); + TimeSpan timeSpan = TimeSpan.FromHours(11); + Duration duration = Duration.FromHours(10); + Assert.True(duration <= timeSpan, "duration should be less than timeSpan"); } [Fact] - public static void ToTimeSpanShouldNotThrowExceptionOnValuesSlightlySmallerThanTimeSpanMax() + public static void DurationGreaterThanOrEqualTimeSpanShouldReturnCorrectly() { - var duration = Duration.FromSeconds(TimeSpan.MaxValue.TotalSeconds - 1); - var timeSpan = duration.ToTimeSpan(); - AssertEx.EqualTolerance(duration.Seconds, timeSpan.TotalSeconds, 1e-3); + TimeSpan timeSpan = TimeSpan.FromHours(11); + Duration duration = Duration.FromHours(12); + Assert.True(duration >= timeSpan, "duration should be greater than timeSpan"); } [Fact] - public static void ToTimeSpanShouldThrowExceptionOnValuesLargerThanTimeSpanMax() + public void DurationTimesVolumeFlowEqualsVolume() { - var duration = Duration.FromSeconds(TimeSpan.MaxValue.TotalSeconds + 1); - Assert.Throws(() => duration.ToTimeSpan()); + Volume volume = Duration.FromSeconds(20) * VolumeFlow.FromCubicMetersPerSecond(2); + Assert.Equal(Volume.FromCubicMeters(40), volume); } - [Fact] - public static void ToTimeSpanShouldThrowExceptionOnValuesSmallerThanTimeSpanMin() + [Theory] + [InlineData("1s", 1)] + [InlineData("2 seconds", 2)] + [InlineData("1 ms", 1e-3)] + [InlineData("1000 msec", 1)] + [InlineData("1 с", 1, "ru-RU")] + [InlineData("1 сек", 1, "ru-RU")] + [InlineData("1000 мс", 1, "ru-RU")] + [InlineData("1000 мсек", 1, "ru-RU")] + public void DurationFromStringUsingMultipleAbbreviationsParsedCorrectly(string textValue, double expectedSeconds, string culture = null) { - var duration = Duration.FromSeconds(TimeSpan.MinValue.TotalSeconds - 1); - Assert.Throws(() => duration.ToTimeSpan()); + var cultureInfo = culture == null ? null : new CultureInfo(culture); + + AssertEx.EqualTolerance(expectedSeconds, Duration.Parse(textValue, cultureInfo).Seconds, SecondsTolerance); } } } diff --git a/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs b/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs index bf03ee2ea8..df79561f7f 100644 --- a/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs +++ b/UnitsNet.Tests/CustomCode/DynamicViscosityTests.cs @@ -1,6 +1,7 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + using Xunit; namespace UnitsNet.Tests.CustomCode @@ -20,7 +21,7 @@ public class DynamicViscosityTests : DynamicViscosityTestsBase [Fact] public static void DynamicViscosityDividedByDensityEqualsKinematicViscosity() { - var kinematicViscosity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(10) / Density.FromKilogramsPerCubicMeter(2); + KinematicViscosity kinematicViscosity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(10) / Density.FromKilogramsPerCubicMeter(2); Assert.Equal(kinematicViscosity, KinematicViscosity.FromSquareMetersPerSecond(5)); } } diff --git a/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs b/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs index 66bb6c89bc..339b51ef65 100644 --- a/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricCurrentTests.cs @@ -31,7 +31,7 @@ public class ElectricCurrentTests : ElectricCurrentTestsBase [InlineData(-10, -2, 20)] public void ElectricCurrentTimesElectricResistanceEqualsElectricPotential(float current, float resistance, float expected) { - var potential = ElectricCurrent.FromAmperes(current) * ElectricResistance.FromOhms(resistance); + ElectricPotential potential = ElectricCurrent.FromAmperes(current) * ElectricResistance.FromOhms(resistance); Assert.Equal(expected, potential.Volts); } } diff --git a/UnitsNet.Tests/CustomCode/ElectricPotentialTests.cs b/UnitsNet.Tests/CustomCode/ElectricPotentialTests.cs index 44e3851f90..4e27fe901e 100644 --- a/UnitsNet.Tests/CustomCode/ElectricPotentialTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricPotentialTests.cs @@ -25,7 +25,7 @@ public class ElectricPotentialTests : ElectricPotentialTestsBase [InlineData(-10, -2, 5)] public void ElectricPotentialDividedByElectricCurrentEqualsElectricResistance(float potential, float current, float expected) { - var resistance = ElectricPotential.FromVolts(potential) / ElectricCurrent.FromAmperes(current); + ElectricResistance resistance = ElectricPotential.FromVolts(potential) / ElectricCurrent.FromAmperes(current); Assert.Equal(expected, resistance.Ohms); } @@ -37,7 +37,7 @@ public void ElectricPotentialDividedByElectricCurrentEqualsElectricResistance(fl [InlineData(-10, -2, 5)] public void ElectricPotentialDividedByElectricResistanceEqualsElectricCurrent(float potential, float resistance, float expected) { - var current = ElectricPotential.FromVolts(potential) / ElectricResistance.FromOhms(resistance); + ElectricCurrent current = ElectricPotential.FromVolts(potential) / ElectricResistance.FromOhms(resistance); Assert.Equal(expected, current.Amperes); } } diff --git a/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs b/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs index 498e2aa53d..bfa15c50bf 100644 --- a/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs +++ b/UnitsNet.Tests/CustomCode/ElectricResistanceTests.cs @@ -25,7 +25,7 @@ public class ElectricResistanceTests : ElectricResistanceTestsBase [InlineData(-10, -2, 20)] public void ElectricResistanceTimesElectricCurrentEqualsElectricPotential(float resistance, float current, float expected) { - var potential = ElectricResistance.FromOhms(resistance) * ElectricCurrent.FromAmperes(current); + ElectricPotential potential = ElectricResistance.FromOhms(resistance) * ElectricCurrent.FromAmperes(current) ; Assert.Equal(expected, potential.Volts); } } diff --git a/UnitsNet.Tests/CustomCode/EnergyTests.cs b/UnitsNet.Tests/CustomCode/EnergyTests.cs index f5ac7e065a..40c00b6547 100644 --- a/UnitsNet.Tests/CustomCode/EnergyTests.cs +++ b/UnitsNet.Tests/CustomCode/EnergyTests.cs @@ -61,17 +61,17 @@ public class EnergyTests : EnergyTestsBase protected override double WattHoursInOneJoule => 0.000277777778; [Fact] - public void As_GivenSIUnitSystem_ReturnsSIValue() + public void Constructor_UnitSystemSI_AssignsSIUnit() { - var btus = new Energy(2.0, EnergyUnit.BritishThermalUnit); - Assert.Equal(2110.11170524, btus.As(UnitSystem.SI)); + var energy = new Energy(1.0, UnitSystem.SI); + Assert.Equal(EnergyUnit.Joule, energy.Unit); } [Fact] - public void Constructor_UnitSystemSI_AssignsSIUnit() + public void As_GivenSIUnitSystem_ReturnsSIValue() { - var energy = new Energy(1.0, UnitSystem.SI); - Assert.Equal(EnergyUnit.Joule, energy.Unit); + var btus = new Energy(2.0, EnergyUnit.BritishThermalUnit); + Assert.Equal(2110.11170524, btus.As(UnitSystem.SI)); } [Fact] diff --git a/UnitsNet.Tests/CustomCode/ForceTests.cs b/UnitsNet.Tests/CustomCode/ForceTests.cs index 48180f7505..34b620ffb7 100644 --- a/UnitsNet.Tests/CustomCode/ForceTests.cs +++ b/UnitsNet.Tests/CustomCode/ForceTests.cs @@ -31,59 +31,59 @@ public class ForceTests : ForceTestsBase protected override double OunceForceInOneNewton => 3.596943089595368; - [Fact] - public void ForceDividedByAccelerationEqualsMass() - { - var acceleration = Force.FromNewtons(200) / Acceleration.FromMetersPerSecondSquared(50); - Assert.Equal(acceleration, Mass.FromKilograms(4)); - } - [Fact] public void ForceDividedByAreaEqualsPressure() { - var pressure = Force.FromNewtons(90) / Area.FromSquareMeters(9); + Pressure pressure = Force.FromNewtons(90)/Area.FromSquareMeters(9); Assert.Equal(pressure, Pressure.FromNewtonsPerSquareMeter(10)); } [Fact] - public void ForceDividedByLengthEqualsForcePerLength() + public void PressureByAreaEqualsForce() { - var forcePerLength = Force.FromNewtons(200) / Length.FromMeters(50); - Assert.Equal(forcePerLength, ForcePerLength.FromNewtonsPerMeter(4)); + Force force = Force.FromPressureByArea(Pressure.FromNewtonsPerSquareMeter(5), Area.FromSquareMeters(7)); + Assert.Equal(force, Force.FromNewtons(35)); } [Fact] public void ForceDividedByMassEqualsAcceleration() { - var acceleration = Force.FromNewtons(27) / Mass.FromKilograms(9); + Acceleration acceleration = Force.FromNewtons(27)/Mass.FromKilograms(9); Assert.Equal(acceleration, Acceleration.FromMetersPerSecondSquared(3)); } [Fact] - public void ForceTimesSpeedEqualsPower() + public void ForceDividedByAccelerationEqualsMass() { - var power = Force.FromNewtons(27.0) * Speed.FromMetersPerSecond(10.0); - Assert.Equal(power, Power.FromWatts(270)); + Mass acceleration = Force.FromNewtons(200)/Acceleration.FromMetersPerSecondSquared(50); + Assert.Equal(acceleration, Mass.FromKilograms(4)); + } + + [Fact] + public void ForceDividedByLengthEqualsForcePerLength() + { + ForcePerLength forcePerLength = Force.FromNewtons(200) / Length.FromMeters(50); + Assert.Equal(forcePerLength, ForcePerLength.FromNewtonsPerMeter(4)); } [Fact] public void MassByAccelerationEqualsForce() { - var force = Force.FromMassByAcceleration(Mass.FromKilograms(85), Acceleration.FromMetersPerSecondSquared(-4)); + Force force = Force.FromMassByAcceleration(Mass.FromKilograms(85), Acceleration.FromMetersPerSecondSquared(-4)); Assert.Equal(force, Force.FromNewtons(-340)); } [Fact] - public void PressureByAreaEqualsForce() + public void ForceTimesSpeedEqualsPower() { - var force = Force.FromPressureByArea(Pressure.FromNewtonsPerSquareMeter(5), Area.FromSquareMeters(7)); - Assert.Equal(force, Force.FromNewtons(35)); + Power power = Force.FromNewtons(27.0)*Speed.FromMetersPerSecond(10.0); + Assert.Equal(power, Power.FromWatts(270)); } [Fact] public void SpeedTimesForceEqualsPower() { - var power = Speed.FromMetersPerSecond(10.0) * Force.FromNewtons(27.0); + Power power = Speed.FromMetersPerSecond(10.0)*Force.FromNewtons(27.0); Assert.Equal(power, Power.FromWatts(270)); } } diff --git a/UnitsNet.Tests/CustomCode/FrequencyTests.cs b/UnitsNet.Tests/CustomCode/FrequencyTests.cs index 7560e91bf5..41253fe566 100644 --- a/UnitsNet.Tests/CustomCode/FrequencyTests.cs +++ b/UnitsNet.Tests/CustomCode/FrequencyTests.cs @@ -21,7 +21,7 @@ public class FrequencyTests : FrequencyTestsBase protected override double CyclesPerMinuteInOneHertz => 60; - protected override double RadiansPerSecondInOneHertz => 2 * Math.PI; + protected override double RadiansPerSecondInOneHertz => 2*Math.PI; protected override double BeatsPerMinuteInOneHertz => 60; } diff --git a/UnitsNet.Tests/CustomCode/IQuantityTests.cs b/UnitsNet.Tests/CustomCode/IQuantityTests.cs index 80ce2d6347..9eda6cd2e8 100644 --- a/UnitsNet.Tests/CustomCode/IQuantityTests.cs +++ b/UnitsNet.Tests/CustomCode/IQuantityTests.cs @@ -9,11 +9,18 @@ namespace UnitsNet.Tests { public partial class IQuantityTests { + [Fact] + public void As_GivenWrongUnitType_ThrowsArgumentException() + { + IQuantity length = Length.FromMeters(1.2345); + Assert.Throws(() => length.As(MassUnit.Kilogram)); + } + [Fact] public void As_GivenNullUnitSystem_ThrowsArgumentNullException() { IQuantity imperialLengthQuantity = new Length(2.0, LengthUnit.Inch); - Assert.Throws(() => imperialLengthQuantity.As((UnitSystem) null)); + Assert.Throws(() => imperialLengthQuantity.As((UnitSystem)null)); } [Fact] @@ -24,17 +31,17 @@ public void As_GivenSIUnitSystem_ReturnsSIValue() } [Fact] - public void As_GivenWrongUnitType_ThrowsArgumentException() + public void ToUnit_GivenWrongUnitType_ThrowsArgumentException() { IQuantity length = Length.FromMeters(1.2345); - Assert.Throws(() => length.As(MassUnit.Kilogram)); + Assert.Throws(() => length.ToUnit(MassUnit.Kilogram)); } [Fact] public void ToUnit_GivenNullUnitSystem_ThrowsArgumentNullException() { IQuantity imperialLengthQuantity = new Length(2.0, LengthUnit.Inch); - Assert.Throws(() => imperialLengthQuantity.ToUnit((UnitSystem) null)); + Assert.Throws(() => imperialLengthQuantity.ToUnit((UnitSystem)null)); } [Fact] @@ -42,17 +49,10 @@ public void ToUnit_GivenSIUnitSystem_ReturnsSIQuantity() { IQuantity inches = new Length(2.0, LengthUnit.Inch); - var inSI = inches.ToUnit(UnitSystem.SI); + IQuantity inSI = inches.ToUnit(UnitSystem.SI); Assert.Equal(0.0508, inSI.Value); Assert.Equal(LengthUnit.Meter, inSI.Unit); } - - [Fact] - public void ToUnit_GivenWrongUnitType_ThrowsArgumentException() - { - IQuantity length = Length.FromMeters(1.2345); - Assert.Throws(() => length.ToUnit(MassUnit.Kilogram)); - } } } diff --git a/UnitsNet.Tests/CustomCode/InformationTests.cs b/UnitsNet.Tests/CustomCode/InformationTests.cs index 4cf999642b..2a7383e8cc 100644 --- a/UnitsNet.Tests/CustomCode/InformationTests.cs +++ b/UnitsNet.Tests/CustomCode/InformationTests.cs @@ -14,69 +14,69 @@ public class InformationTests : InformationTestsBase protected override double ExabitsInOneBit => 1e-18d; - protected override double ExabytesInOneBit => 0.125d * 1e-18d; + protected override double ExabytesInOneBit => 0.125d*1e-18d; - protected override double ExbibitsInOneBit => 1d / Math.Pow(1024, 6); + protected override double ExbibitsInOneBit => 1d/Math.Pow(1024, 6); - protected override double ExbibytesInOneBit => 1 / 8d / Math.Pow(1024, 6); + protected override double ExbibytesInOneBit => 1/8d/Math.Pow(1024, 6); - protected override double GibibitsInOneBit => 1d / Math.Pow(1024, 3); + protected override double GibibitsInOneBit => 1d/Math.Pow(1024, 3); - protected override double GibibytesInOneBit => 1d / 8 / Math.Pow(1024, 3); + protected override double GibibytesInOneBit => 1d/8/Math.Pow(1024, 3); protected override double GigabitsInOneBit => 1e-9d; - protected override double GigabytesInOneBit => 0.125d * 1e-9d; + protected override double GigabytesInOneBit => 0.125d*1e-9d; - protected override double KibibitsInOneBit => 1d / 1024d; + protected override double KibibitsInOneBit => 1d/1024d; - protected override double KibibytesInOneBit => 1d / 8 / 1024d; + protected override double KibibytesInOneBit => 1d/8/1024d; protected override double KilobitsInOneBit => 0.001d; protected override double KilobytesInOneBit => 0.000125d; - protected override double MebibitsInOneBit => 1d / Math.Pow(1024, 2); + protected override double MebibitsInOneBit => 1d/Math.Pow(1024, 2); - protected override double MebibytesInOneBit => 1d / 8 / Math.Pow(1024, 2); + protected override double MebibytesInOneBit => 1d/8/Math.Pow(1024, 2); protected override double MegabitsInOneBit => 1e-6d; - protected override double MegabytesInOneBit => 0.125d * 1e-6d; + protected override double MegabytesInOneBit => 0.125d*1e-6d; - protected override double PebibitsInOneBit => 1d / Math.Pow(1024, 5); + protected override double PebibitsInOneBit => 1d/Math.Pow(1024, 5); - protected override double PebibytesInOneBit => 1d / 8 / Math.Pow(1024, 5); + protected override double PebibytesInOneBit => 1d/8/Math.Pow(1024, 5); protected override double PetabitsInOneBit => 1e-15d; - protected override double PetabytesInOneBit => 0.125d * 1e-15d; + protected override double PetabytesInOneBit => 0.125d*1e-15d; - protected override double TebibitsInOneBit => 1d / Math.Pow(1024, 4); + protected override double TebibitsInOneBit => 1d/Math.Pow(1024, 4); - protected override double TebibytesInOneBit => 1d / 8 / Math.Pow(1024, 4); + protected override double TebibytesInOneBit => 1d/8/Math.Pow(1024, 4); protected override double TerabitsInOneBit => 1e-12d; - protected override double TerabytesInOneBit => 0.125d * 1e-12d; + protected override double TerabytesInOneBit => 0.125d*1e-12d; +// ReSharper disable once InconsistentNaming [Fact] - public void MaxValueIsCorrectForUnitWithBaseTypeDecimal() + public void OneKBHas1000Bytes() { - Assert.Equal((double) decimal.MaxValue, Information.MaxValue.Bits); + Assert.Equal(1000, Information.FromKilobytes(1).Bytes); } [Fact] - public void MinValueIsCorrectForUnitWithBaseTypeDecimal() + public void MaxValueIsCorrectForUnitWithBaseTypeDecimal() { - Assert.Equal((double) decimal.MinValue, Information.MinValue.Bits); + Assert.Equal((double) decimal.MaxValue, Information.MaxValue.Bits); } -// ReSharper disable once InconsistentNaming [Fact] - public void OneKBHas1000Bytes() + public void MinValueIsCorrectForUnitWithBaseTypeDecimal() { - Assert.Equal(1000, Information.FromKilobytes(1).Bytes); + Assert.Equal((double) decimal.MinValue, Information.MinValue.Bits); } } } diff --git a/UnitsNet.Tests/CustomCode/KinematicViscosityTests.cs b/UnitsNet.Tests/CustomCode/KinematicViscosityTests.cs index 5ec32cdc9a..f41e2d5d54 100644 --- a/UnitsNet.Tests/CustomCode/KinematicViscosityTests.cs +++ b/UnitsNet.Tests/CustomCode/KinematicViscosityTests.cs @@ -27,43 +27,43 @@ public class KinematicViscosityTests : KinematicViscosityTestsBase [Fact] public static void DurationTimesKinematicViscosityEqualsArea() { - var area = Duration.FromSeconds(2) * KinematicViscosity.FromSquareMetersPerSecond(4); + Area area = Duration.FromSeconds(2)*KinematicViscosity.FromSquareMetersPerSecond(4); Assert.Equal(area, Area.FromSquareMeters(8)); } [Fact] public static void KinematicViscosityDividedByLengthEqualsSpeed() { - var speed = KinematicViscosity.FromSquareMetersPerSecond(4) / Length.FromMeters(2); + Speed speed = KinematicViscosity.FromSquareMetersPerSecond(4)/Length.FromMeters(2); Assert.Equal(speed, Speed.FromMetersPerSecond(2)); } - [Fact] - public static void KinematicViscosityTimesDensityEqualsDynamicViscosity() - { - var dynamicViscosity = KinematicViscosity.FromSquareMetersPerSecond(10) * Density.FromKilogramsPerCubicMeter(2); - Assert.Equal(dynamicViscosity, DynamicViscosity.FromNewtonSecondsPerMeterSquared(20)); - } - [Fact] public static void KinematicViscosityTimesDurationEqualsArea() { - var area = KinematicViscosity.FromSquareMetersPerSecond(4) * Duration.FromSeconds(2); + Area area = KinematicViscosity.FromSquareMetersPerSecond(4)*Duration.FromSeconds(2); Assert.Equal(area, Area.FromSquareMeters(8)); } [Fact] public static void KinematicViscosityTimesTimeSpanEqualsArea() { - var area = KinematicViscosity.FromSquareMetersPerSecond(4) * TimeSpan.FromSeconds(2); + Area area = KinematicViscosity.FromSquareMetersPerSecond(4)*TimeSpan.FromSeconds(2); Assert.Equal(area, Area.FromSquareMeters(8)); } [Fact] public static void TimeSpanTimesKinematicViscosityEqualsArea() { - var area = TimeSpan.FromSeconds(2) * KinematicViscosity.FromSquareMetersPerSecond(4); + Area area = TimeSpan.FromSeconds(2)*KinematicViscosity.FromSquareMetersPerSecond(4); Assert.Equal(area, Area.FromSquareMeters(8)); } + + [Fact] + public static void KinematicViscosityTimesDensityEqualsDynamicViscosity() + { + DynamicViscosity dynamicViscosity = KinematicViscosity.FromSquareMetersPerSecond(10) * Density.FromKilogramsPerCubicMeter(2); + Assert.Equal(dynamicViscosity, DynamicViscosity.FromNewtonSecondsPerMeterSquared(20)); + } } } diff --git a/UnitsNet.Tests/CustomCode/KnownQuantities.cs b/UnitsNet.Tests/CustomCode/KnownQuantities.cs index 8469efab84..0a3b8a9b37 100644 --- a/UnitsNet.Tests/CustomCode/KnownQuantities.cs +++ b/UnitsNet.Tests/CustomCode/KnownQuantities.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -namespace UnitsNet.Tests.CustomCode +namespace UnitsNet.Tests.CustomCode { public static class KnownQuantities { diff --git a/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs b/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs index fb835ae18d..c07c02af5f 100644 --- a/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs +++ b/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs @@ -12,6 +12,23 @@ public class FeetInchesTests private const double FeetTolerance = 1e-5; private const double InchesTolerance = 1e-5; + [Fact] + public void FeetInchesFrom() + { + Length meter = Length.FromFeetInches(2, 3); + double expectedMeters = 2/FeetInOneMeter + 3/InchesInOneMeter; + AssertEx.EqualTolerance(expectedMeters, meter.Meters, FeetTolerance); + } + + [Fact] + public void FeetInchesRoundTrip() + { + Length meter = Length.FromFeetInches(2, 3); + FeetInches feetInches = meter.FeetInches; + AssertEx.EqualTolerance(2, feetInches.Feet, FeetTolerance); + AssertEx.EqualTolerance(3, feetInches.Inches, InchesTolerance); + } + [Theory] [InlineData("1'", 1)] // Feet only [InlineData("1′", 1)] // Feet only @@ -45,7 +62,7 @@ public class FeetInchesTests [InlineData("-1ft 1in", -1.08333333)] public void TryParseFeetInches(string str, double expectedFeet) { - Assert.True(Length.TryParseFeetInches(str, out var result)); + Assert.True(Length.TryParseFeetInches(str, out Length result)); AssertEx.EqualTolerance(expectedFeet, result.Feet, 1e-5); } @@ -68,25 +85,8 @@ public void TryParseFeetInches(string str, double expectedFeet) [InlineData("1'1`")] public void TryParseFeetInches_GivenInvalidString_ReturnsFalseAndZeroOut(string str) { - Assert.False(Length.TryParseFeetInches(str, out var result)); + Assert.False(Length.TryParseFeetInches(str, out Length result)); Assert.Equal(Length.Zero, result); } - - [Fact] - public void FeetInchesFrom() - { - var meter = Length.FromFeetInches(2, 3); - var expectedMeters = 2 / FeetInOneMeter + 3 / InchesInOneMeter; - AssertEx.EqualTolerance(expectedMeters, meter.Meters, FeetTolerance); - } - - [Fact] - public void FeetInchesRoundTrip() - { - var meter = Length.FromFeetInches(2, 3); - var feetInches = meter.FeetInches; - AssertEx.EqualTolerance(2, feetInches.Feet, FeetTolerance); - AssertEx.EqualTolerance(3, feetInches.Inches, InchesTolerance); - } } } diff --git a/UnitsNet.Tests/CustomCode/LengthTests.cs b/UnitsNet.Tests/CustomCode/LengthTests.cs index fef6177f2c..d5dc4f4d8e 100644 --- a/UnitsNet.Tests/CustomCode/LengthTests.cs +++ b/UnitsNet.Tests/CustomCode/LengthTests.cs @@ -1,9 +1,9 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using System; -using UnitsNet.Units; using Xunit; +using UnitsNet.Units; +using System; namespace UnitsNet.Tests.CustomCode { @@ -53,7 +53,7 @@ public class LengthTests : LengthTestsBase protected override double ShacklesInOneMeter => 0.0364538; - protected override double NauticalMilesInOneMeter => 1.0 / 1852.0; + protected override double NauticalMilesInOneMeter => 1.0/1852.0; protected override double HandsInOneMeter => 9.8425196850393701; @@ -73,87 +73,76 @@ public class LengthTests : LengthTestsBase protected override double SolarRadiusesInOneMeter => 1.43779384911791000E-09; - [Fact] + [ Fact] public void AreaTimesLengthEqualsVolume() { - var volume = Area.FromSquareMeters(10) * Length.FromMeters(3); + Volume volume = Area.FromSquareMeters(10)*Length.FromMeters(3); Assert.Equal(volume, Volume.FromCubicMeters(30)); } [Fact] - public void As_GivenSIUnitSystem_ReturnsSIValue() - { - var inches = new Length(2.0, LengthUnit.Inch); - Assert.Equal(0.0508, inches.As(UnitSystem.SI)); - } - - [Fact] - public void Constructor_UnitSystemNull_ThrowsArgumentNullException() + public void ForceTimesLengthEqualsTorque() { - Assert.Throws(() => new Length(1.0, null)); + Torque torque = Force.FromNewtons(1)*Length.FromMeters(3); + Assert.Equal(torque, Torque.FromNewtonMeters(3)); } [Fact] - public void Constructor_UnitSystemSI_AssignsSIUnit() + public void LengthTimesAreaEqualsVolume() { - var length = new Length(1.0, UnitSystem.SI); - Assert.Equal(LengthUnit.Meter, length.Unit); + Volume volume = Length.FromMeters(3)*Area.FromSquareMeters(9); + Assert.Equal(volume, Volume.FromCubicMeters(27)); } [Fact] - public void Constructor_UnitSystemWithNoMatchingBaseUnits_ThrowsArgumentException() + public void LengthTimesForceEqualsTorque() { - // AmplitudeRatio is unitless. Can't have any matches :) - Assert.Throws(() => new AmplitudeRatio(1.0, UnitSystem.SI)); + Torque torque = Length.FromMeters(3)*Force.FromNewtons(1); + Assert.Equal(torque, Torque.FromNewtonMeters(3)); } [Fact] - public void ForceTimesLengthEqualsTorque() + public void LengthTimesLengthEqualsArea() { - var torque = Force.FromNewtons(1) * Length.FromMeters(3); - Assert.Equal(torque, Torque.FromNewtonMeters(3)); + Area area = Length.FromMeters(10)*Length.FromMeters(2); + Assert.Equal(area, Area.FromSquareMeters(20)); } [Fact] public void LengthDividedBySpeedEqualsDuration() { - var duration = Length.FromMeters(20) / Speed.FromMetersPerSecond(2); + Duration duration = Length.FromMeters(20) / Speed.FromMetersPerSecond(2); Assert.Equal(Duration.FromSeconds(10), duration); } [Fact] - public void LengthTimesAreaEqualsVolume() - { - var volume = Length.FromMeters(3) * Area.FromSquareMeters(9); - Assert.Equal(volume, Volume.FromCubicMeters(27)); - } - - [Fact] - public void LengthTimesForceEqualsTorque() + public void LengthTimesSpeedEqualsKinematicViscosity() { - var torque = Length.FromMeters(3) * Force.FromNewtons(1); - Assert.Equal(torque, Torque.FromNewtonMeters(3)); + KinematicViscosity kinematicViscosity = Length.FromMeters(20) * Speed.FromMetersPerSecond(2); + Assert.Equal(KinematicViscosity.FromSquareMetersPerSecond(40), kinematicViscosity); } [Fact] - public void LengthTimesLengthEqualsArea() + public void LengthTimesSpecificWeightEqualsPressure() { - var area = Length.FromMeters(10) * Length.FromMeters(2); - Assert.Equal(area, Area.FromSquareMeters(20)); + Pressure pressure = Length.FromMeters(2) * SpecificWeight.FromNewtonsPerCubicMeter(10); + Assert.Equal(Pressure.FromPascals(20), pressure); } [Fact] - public void LengthTimesSpecificWeightEqualsPressure() + public void ToStringReturnsCorrectNumberAndUnitWithDefaultUnitWhichIsMeter() { - var pressure = Length.FromMeters(2) * SpecificWeight.FromNewtonsPerCubicMeter(10); - Assert.Equal(Pressure.FromPascals(20), pressure); + var meter = Length.FromMeters(5); + string meterString = meter.ToString(); + Assert.Equal("5 m", meterString); } [Fact] - public void LengthTimesSpeedEqualsKinematicViscosity() + public void ToStringReturnsCorrectNumberAndUnitWithCentimeterAsDefualtUnit() { - var kinematicViscosity = Length.FromMeters(20) * Speed.FromMetersPerSecond(2); - Assert.Equal(KinematicViscosity.FromSquareMetersPerSecond(40), kinematicViscosity); + var value = Length.From(2, LengthUnit.Centimeter); + string valueString = value.ToString(); + Assert.Equal("2 cm", valueString); } [Fact] @@ -185,19 +174,30 @@ public void NegativeLengthToStonePoundsReturnsCorrectValues() } [Fact] - public void ToStringReturnsCorrectNumberAndUnitWithCentimeterAsDefualtUnit() + public void Constructor_UnitSystemNull_ThrowsArgumentNullException() { - var value = Length.From(2, LengthUnit.Centimeter); - var valueString = value.ToString(); - Assert.Equal("2 cm", valueString); + Assert.Throws(() => new Length(1.0, (UnitSystem)null)); } [Fact] - public void ToStringReturnsCorrectNumberAndUnitWithDefaultUnitWhichIsMeter() + public void Constructor_UnitSystemSI_AssignsSIUnit() { - var meter = Length.FromMeters(5); - var meterString = meter.ToString(); - Assert.Equal("5 m", meterString); + var length = new Length(1.0, UnitSystem.SI); + Assert.Equal(LengthUnit.Meter, length.Unit); + } + + [Fact] + public void Constructor_UnitSystemWithNoMatchingBaseUnits_ThrowsArgumentException() + { + // AmplitudeRatio is unitless. Can't have any matches :) + Assert.Throws(() => new AmplitudeRatio(1.0, UnitSystem.SI)); + } + + [Fact] + public void As_GivenSIUnitSystem_ReturnsSIValue() + { + var inches = new Length(2.0, LengthUnit.Inch); + Assert.Equal(0.0508, inches.As(UnitSystem.SI)); } [Fact] diff --git a/UnitsNet.Tests/CustomCode/LevelTests.cs b/UnitsNet.Tests/CustomCode/LevelTests.cs index 7a46941166..e5d81b2eb8 100644 --- a/UnitsNet.Tests/CustomCode/LevelTests.cs +++ b/UnitsNet.Tests/CustomCode/LevelTests.cs @@ -14,13 +14,13 @@ public class LevelTests : LevelTestsBase protected override void AssertLogarithmicAddition() { - var v = Level.FromDecibels(40); + Level v = Level.FromDecibels(40); AssertEx.EqualTolerance(43.0102999566, (v + v).Decibels, DecibelsTolerance); } protected override void AssertLogarithmicSubtraction() { - var v = Level.FromDecibels(40); + Level v = Level.FromDecibels(40); AssertEx.EqualTolerance(49.5424250944, (Level.FromDecibels(50) - v).Decibels, DecibelsTolerance); } diff --git a/UnitsNet.Tests/CustomCode/MassFlowTests.cs b/UnitsNet.Tests/CustomCode/MassFlowTests.cs index 2e64d25c0f..b407d74dfa 100644 --- a/UnitsNet.Tests/CustomCode/MassFlowTests.cs +++ b/UnitsNet.Tests/CustomCode/MassFlowTests.cs @@ -79,78 +79,78 @@ public class MassFlowTests : MassFlowTestsBase [Fact] public void DurationTimesMassFlowEqualsMass() { - var mass = Duration.FromSeconds(4.0) * MassFlow.FromKilogramsPerSecond(20.0); + Mass mass = Duration.FromSeconds(4.0) * MassFlow.FromKilogramsPerSecond(20.0); Assert.Equal(mass, Mass.FromKilograms(80.0)); } [Fact] - public void MassFlowDividedByAreaEqualsMassFlux() + public void MassFlowTimesDurationEqualsMass() { - var massFlux = MassFlow.FromKilogramsPerSecond(20) / Area.FromSquareMeters(2); - Assert.Equal(10, massFlux.KilogramsPerSecondPerSquareMeter); + Mass mass = MassFlow.FromKilogramsPerSecond(20.0) * Duration.FromSeconds(4.0); + Assert.Equal(mass, Mass.FromKilograms(80.0)); } [Fact] - public void MassFlowDividedByBrakeSpecificFuelConsumptionEqualsPower() + public void MassFlowTimesTimeSpanEqualsMass() { - var power = MassFlow.FromTonnesPerDay(20) / BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0); - Assert.Equal(20.0 / 24.0 * 1e6 / 180.0, power.Kilowatts); + Mass mass = MassFlow.FromKilogramsPerSecond(20.0) * TimeSpan.FromSeconds(4.0); + Assert.Equal(mass, Mass.FromKilograms(80.0)); } [Fact] - public void MassFlowDividedByDensityEqualsVolumeFlow() + public void TimeSpanTimesMassFlowEqualsMass() { - var volumeFlow = MassFlow.FromKilogramsPerSecond(20) / Density.FromKilogramsPerCubicMeter(4); - Assert.Equal(5, volumeFlow.CubicMetersPerSecond); + Mass mass = TimeSpan.FromSeconds(4.0) * MassFlow.FromKilogramsPerSecond(20.0); + Assert.Equal(mass, Mass.FromKilograms(80.0)); } [Fact] - public void MassFlowDividedByMassFluxEqualsArea() + public void MassFlowDividedByBrakeSpecificFuelConsumptionEqualsPower() { - var area = MassFlow.FromKilogramsPerSecond(20) / MassFlux.FromKilogramsPerSecondPerSquareMeter(2); - Assert.Equal(10, area.SquareMeters); + Power power = MassFlow.FromTonnesPerDay(20) / BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0); + Assert.Equal(20.0 / 24.0 * 1e6 / 180.0, power.Kilowatts); } [Fact] public void MassFlowDividedByPowerEqualsBrakeSpecificFuelConsumption() { - var bsfc = MassFlow.FromTonnesPerDay(20) / Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0); + BrakeSpecificFuelConsumption bsfc = MassFlow.FromTonnesPerDay(20) / Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0); AssertEx.EqualTolerance(180.0, bsfc.GramsPerKiloWattHour, 1e-11); } [Fact] - public void MassFlowDividedByVolumeFlowEqualsDensity() + public void MassFlowTimesSpecificEnergyEqualsPower() { - var density = MassFlow.FromKilogramsPerSecond(12) / VolumeFlow.FromCubicMetersPerSecond(3); - Assert.Equal(4, density.KilogramsPerCubicMeter); + Power power = MassFlow.FromKilogramsPerSecond(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); + Assert.Equal(200, power.Watts); } [Fact] - public void MassFlowTimesDurationEqualsMass() + public void MassFlowDividedByAreaEqualsMassFlux() { - var mass = MassFlow.FromKilogramsPerSecond(20.0) * Duration.FromSeconds(4.0); - Assert.Equal(mass, Mass.FromKilograms(80.0)); + MassFlux massFlux = MassFlow.FromKilogramsPerSecond(20) / Area.FromSquareMeters(2); + Assert.Equal(10, massFlux.KilogramsPerSecondPerSquareMeter); } [Fact] - public void MassFlowTimesSpecificEnergyEqualsPower() + public void MassFlowDividedByMassFluxEqualsArea() { - var power = MassFlow.FromKilogramsPerSecond(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); - Assert.Equal(200, power.Watts); + Area area = MassFlow.FromKilogramsPerSecond(20) / MassFlux.FromKilogramsPerSecondPerSquareMeter(2); + Assert.Equal(10, area.SquareMeters); } [Fact] - public void MassFlowTimesTimeSpanEqualsMass() + public void MassFlowDividedByVolumeFlowEqualsDensity() { - var mass = MassFlow.FromKilogramsPerSecond(20.0) * TimeSpan.FromSeconds(4.0); - Assert.Equal(mass, Mass.FromKilograms(80.0)); + Density density = MassFlow.FromKilogramsPerSecond(12) / VolumeFlow.FromCubicMetersPerSecond(3); + Assert.Equal(4, density.KilogramsPerCubicMeter); } [Fact] - public void TimeSpanTimesMassFlowEqualsMass() + public void MassFlowDividedByDensityEqualsVolumeFlow() { - var mass = TimeSpan.FromSeconds(4.0) * MassFlow.FromKilogramsPerSecond(20.0); - Assert.Equal(mass, Mass.FromKilograms(80.0)); + VolumeFlow volumeFlow = MassFlow.FromKilogramsPerSecond(20) / Density.FromKilogramsPerCubicMeter(4); + Assert.Equal(5, volumeFlow.CubicMetersPerSecond); } } } diff --git a/UnitsNet.Tests/CustomCode/MassTests.cs b/UnitsNet.Tests/CustomCode/MassTests.cs index 0c501f2519..18cb904f33 100644 --- a/UnitsNet.Tests/CustomCode/MassTests.cs +++ b/UnitsNet.Tests/CustomCode/MassTests.cs @@ -61,57 +61,40 @@ public class MassTests : MassTestsBase protected override double SolarMassesInOneKilogram => 5.0264643347223100000000000E-31; - [Theory] - [InlineData(10, MassUnit.Gram, - KnownQuantities.MolarMassOfOxygen, MolarMassUnit.GramPerMole, - 0.625023438378939, AmountOfSubstanceUnit.Mole)] // 10 grams Of Oxygen contain 0.625023438378939 Moles - public void AmountOfSubstanceFromMassAndMolarMass( - double massValue, MassUnit massUnit, - double molarMassValue, MolarMassUnit molarMassUnit, - double expectedAmountOfSubstanceValue, AmountOfSubstanceUnit expectedAmountOfSubstanceUnit, double tolerence = 1e-5) - { - var mass = new Mass(massValue, massUnit); - var molarMass = new MolarMass(molarMassValue, molarMassUnit); - - var amountOfSubstance = mass / molarMass; - - AssertEx.EqualTolerance(expectedAmountOfSubstanceValue, amountOfSubstance.As(expectedAmountOfSubstanceUnit), tolerence); - } - //protected override double SolarMassesTolerance => 0.1; [Fact] public void AccelerationTimesMassEqualsForce() { - var force = Acceleration.FromMetersPerSecondSquared(3) * Mass.FromKilograms(18); + Force force = Acceleration.FromMetersPerSecondSquared(3)*Mass.FromKilograms(18); Assert.Equal(force, Force.FromNewtons(54)); } [Fact] public void MassDividedByDurationEqualsMassFlow() { - var massFlow = Mass.FromKilograms(18.0) / Duration.FromSeconds(6); + MassFlow massFlow = Mass.FromKilograms(18.0)/Duration.FromSeconds(6); Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(3.0)); } [Fact] public void MassDividedByTimeSpanEqualsMassFlow() { - var massFlow = Mass.FromKilograms(18.0) / TimeSpan.FromSeconds(6); + MassFlow massFlow = Mass.FromKilograms(18.0)/TimeSpan.FromSeconds(6); Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(3.0)); } [Fact] public void MassDividedByVolumeEqualsDensity() { - var density = Mass.FromKilograms(18) / Volume.FromCubicMeters(3); + Density density = Mass.FromKilograms(18)/Volume.FromCubicMeters(3); Assert.Equal(density, Density.FromKilogramsPerCubicMeter(6)); } [Fact] public void MassTimesAccelerationEqualsForce() { - var force = Mass.FromKilograms(18) * Acceleration.FromMetersPerSecondSquared(3); + Force force = Mass.FromKilograms(18)*Acceleration.FromMetersPerSecondSquared(3); Assert.Equal(force, Force.FromNewtons(54)); } @@ -130,5 +113,22 @@ public void NegativeMassToStonePoundsReturnsCorrectValues() Assert.Equal(-1.0, stonePounds.Stone); Assert.Equal(-11.0, stonePounds.Pounds); } + + [Theory] + [InlineData(10, MassUnit.Gram, + KnownQuantities.MolarMassOfOxygen, MolarMassUnit.GramPerMole, + 0.625023438378939, AmountOfSubstanceUnit.Mole)] // 10 grams Of Oxygen contain 0.625023438378939 Moles + public void AmountOfSubstanceFromMassAndMolarMass( + double massValue, MassUnit massUnit, + double molarMassValue, MolarMassUnit molarMassUnit, + double expectedAmountOfSubstanceValue, AmountOfSubstanceUnit expectedAmountOfSubstanceUnit, double tolerence = 1e-5) + { + var mass = new Mass(massValue, massUnit); + var molarMass = new MolarMass(molarMassValue, molarMassUnit); + + AmountOfSubstance amountOfSubstance = mass / molarMass; + + AssertEx.EqualTolerance(expectedAmountOfSubstanceValue, amountOfSubstance.As(expectedAmountOfSubstanceUnit), tolerence); + } } } diff --git a/UnitsNet.Tests/CustomCode/ParseTests.cs b/UnitsNet.Tests/CustomCode/ParseTests.cs index 29f18928f3..06a1f7cdc9 100644 --- a/UnitsNet.Tests/CustomCode/ParseTests.cs +++ b/UnitsNet.Tests/CustomCode/ParseTests.cs @@ -27,8 +27,8 @@ public class ParseTests [InlineData("500,005 m", 500005)] public void ParseLengthToMetersUsEnglish(string s, double expected) { - var usEnglish = new CultureInfo("en-US"); - var actual = Length.Parse(s, usEnglish).Meters; + CultureInfo usEnglish = new CultureInfo("en-US"); + double actual = Length.Parse(s, usEnglish).Meters; Assert.Equal(expected, actual); } @@ -58,7 +58,7 @@ public void ParseWithCultureUsingSpaceAsThousandSeparators(string s, double expe numberFormat.NumberDecimalSeparator = "."; numberFormat.CurrencyDecimalSeparator = "."; - var actual = Length.Parse(s, numberFormat).Meters; + double actual = Length.Parse(s, numberFormat).Meters; Assert.Equal(expected, actual); } @@ -89,10 +89,17 @@ public void ParseWithCultureUsingDotAsThousandSeparators(string s, double expect numberFormat.NumberDecimalSeparator = ","; numberFormat.CurrencyDecimalSeparator = ","; - var actual = Length.Parse(s, numberFormat).Meters; + double actual = Length.Parse(s, numberFormat).Meters; Assert.Equal(expected, actual); } + [Fact] + public void ParseMultiWordAbbreviations() + { + Assert.Equal(Mass.FromShortTons(333), Mass.Parse("333 short tn")); + Assert.Equal(Mass.FromLongTons(333), Mass.Parse("333 long tn")); + } + [Theory] [InlineData("500 005 m", typeof(FormatException))] // Quantity doesn't match number format. public void ParseWithCultureUsingDotAsThousandSeparators_ThrowsExceptionOnInvalidString(string s, Type expectedExceptionType) @@ -110,8 +117,8 @@ public void ParseWithCultureUsingDotAsThousandSeparators_ThrowsExceptionOnInvali [InlineData("m", LengthUnit.Meter)] public void ParseLengthUnitUsEnglish(string s, LengthUnit expected) { - var usEnglish = new CultureInfo("en-US"); - var actual = Length.ParseUnit(s, usEnglish); + CultureInfo usEnglish = new CultureInfo("en-US"); + LengthUnit actual = Length.ParseUnit(s, usEnglish); Assert.Equal(expected, actual); } @@ -132,8 +139,8 @@ public void ParseLengthUnitUsEnglish_ThrowsExceptionOnInvalidString(string s, Ty [InlineData("foo", false)] public void TryParseLengthUnitUsEnglish(string s, bool expected) { - var usEnglish = new CultureInfo("en-US"); - var actual = Length.TryParse(s, usEnglish, out _); + CultureInfo usEnglish = new CultureInfo("en-US"); + bool actual = Length.TryParse(s, usEnglish, out Length _); Assert.Equal(expected, actual); } @@ -144,8 +151,7 @@ public void TryParseLengthUnitUsEnglish(string s, bool expected) [InlineData("1 г", "ru-RU", 1, MassUnit.Gram)] [InlineData("1 kg", "en-US", 1, MassUnit.Kilogram)] [InlineData("1 кг", "ru-RU", 1, MassUnit.Kilogram)] - public void ParseMassWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, - Enum expectedUnit) + public void ParseMassWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, Enum expectedUnit) { var actual = Mass.Parse(str, new CultureInfo(cultureName)); @@ -160,8 +166,7 @@ public void ParseMassWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAnd [InlineData("1 м", "ru-RU", 1, LengthUnit.Meter)] [InlineData("1 km", "en-US", 1, LengthUnit.Kilometer)] [InlineData("1 км", "ru-RU", 1, LengthUnit.Kilometer)] - public void ParseLengthWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, - Enum expectedUnit) + public void ParseLengthWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, Enum expectedUnit) { var actual = Length.Parse(str, new CultureInfo(cultureName)); @@ -176,8 +181,7 @@ public void ParseLengthWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitA [InlineData("1 Н", "ru-RU", 1, ForceUnit.Newton)] [InlineData("1 kN", "en-US", 1, ForceUnit.Kilonewton)] [InlineData("1 кН", "ru-RU", 1, ForceUnit.Kilonewton)] - public void ParseForceWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, - Enum expectedUnit) + public void ParseForceWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, double expectedValue, Enum expectedUnit) { var actual = Force.Parse(str, new CultureInfo(cultureName)); @@ -198,20 +202,12 @@ public void ParseForceWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAn [InlineData("1 MB", "ru-RU", 1, InformationUnit.Megabyte)] [InlineData("1 MiB", "en-US", 1, InformationUnit.Mebibyte)] [InlineData("1 MiB", "ru-RU", 1, InformationUnit.Mebibyte)] - public void ParseInformationWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, decimal expectedValue, - Enum expectedUnit) + public void ParseInformationWithPrefixUnits_GivenCulture_ReturnsQuantityWithSameUnitAndValue(string str, string cultureName, decimal expectedValue, Enum expectedUnit) { var actual = Information.Parse(str, new CultureInfo(cultureName)); Assert.Equal(expectedUnit, actual.Unit); Assert.Equal(expectedValue, actual.Value); } - - [Fact] - public void ParseMultiWordAbbreviations() - { - Assert.Equal(Mass.FromShortTons(333), Mass.Parse("333 short tn")); - Assert.Equal(Mass.FromLongTons(333), Mass.Parse("333 long tn")); - } } } diff --git a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs index 5e8e287a1e..896c60b9bc 100644 --- a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs @@ -14,13 +14,13 @@ public class PowerRatioTests : PowerRatioTestsBase protected override void AssertLogarithmicAddition() { - var v = PowerRatio.FromDecibelWatts(40); + PowerRatio v = PowerRatio.FromDecibelWatts(40); AssertEx.EqualTolerance(43.0102999566, (v + v).DecibelWatts, DecibelWattsTolerance); } protected override void AssertLogarithmicSubtraction() { - var v = PowerRatio.FromDecibelWatts(40); + PowerRatio v = PowerRatio.FromDecibelWatts(40); AssertEx.EqualTolerance(49.5424250944, (PowerRatio.FromDecibelWatts(50) - v).DecibelWatts, DecibelWattsTolerance); } @@ -39,8 +39,8 @@ public void InvalidPower_ExpectArgumentOutOfRangeException(double power) [InlineData(100, 20)] public void ExpectPowerConvertedCorrectly(double power, double expected) { - var p = Power.FromWatts(power); - var actual = PowerRatio.FromPower(p).DecibelWatts; + Power p = Power.FromWatts(power); + double actual = PowerRatio.FromPower(p).DecibelWatts; Assert.Equal(expected, actual); } @@ -52,8 +52,8 @@ public void ExpectPowerConvertedCorrectly(double power, double expected) [InlineData(20, 100)] public void ExpectPowerRatioConvertedCorrectly(double powerRatio, double expected) { - var pr = PowerRatio.FromDecibelWatts(powerRatio); - var actual = pr.ToPower().Watts; + PowerRatio pr = PowerRatio.FromDecibelWatts(powerRatio); + double actual = pr.ToPower().Watts; Assert.Equal(expected, actual); } @@ -66,9 +66,9 @@ public void ExpectPowerRatioConvertedCorrectly(double powerRatio, double expecte [InlineData(-6.99, 40)] public void PowerRatioToAmplitudeRatio_50OhmImpedance(double dBmW, double expected) { - var powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); + PowerRatio powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); - var actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(50)).DecibelMillivolts, 2); + double actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(50)).DecibelMillivolts, 2); Assert.Equal(expected, actual); } @@ -79,9 +79,9 @@ public void PowerRatioToAmplitudeRatio_50OhmImpedance(double dBmW, double expect [InlineData(-8.75, 40)] public void PowerRatioToAmplitudeRatio_75OhmImpedance(double dBmW, double expected) { - var powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); + PowerRatio powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); - var actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(75)).DecibelMillivolts, 2); + double actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(75)).DecibelMillivolts, 2); Assert.Equal(expected, actual); } } diff --git a/UnitsNet.Tests/CustomCode/PowerTests.cs b/UnitsNet.Tests/CustomCode/PowerTests.cs index bd6f6a18ad..45821fdb81 100644 --- a/UnitsNet.Tests/CustomCode/PowerTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerTests.cs @@ -61,71 +61,71 @@ public class PowerTests : PowerTestsBase [Fact] public void DurationTimesPowerEqualsEnergy() { - var energy = Duration.FromSeconds(8.0) * Power.FromWatts(5.0); + Energy energy = Duration.FromSeconds(8.0) * Power.FromWatts(5.0); Assert.Equal(energy, Energy.FromJoules(40.0)); } - [Fact] - public void PowerDividedByMassFlowEqualsSpecificEnergy() - { - var specificEnergy = Power.FromWatts(15.0) / MassFlow.FromKilogramsPerSecond(3); - Assert.Equal(specificEnergy, SpecificEnergy.FromJoulesPerKilogram(5)); - } - [Fact] public void PowerDividedByRotationalSpeedEqualsForce() { - var torque = Power.FromWatts(15.0) / RotationalSpeed.FromRadiansPerSecond(3); + Torque torque = Power.FromWatts(15.0) / RotationalSpeed.FromRadiansPerSecond(3); Assert.Equal(torque, Torque.FromNewtonMeters(5)); } - [Fact] - public void PowerDividedBySpecificEnergyEqualsMassFlow() - { - var massFlow = Power.FromWatts(15.0) / SpecificEnergy.FromJoulesPerKilogram(3); - Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(5)); - } - [Fact] public void PowerDividedBySpeedEqualsForce() { - var force = Power.FromWatts(15.0) / Speed.FromMetersPerSecond(3); + Force force = Power.FromWatts(15.0) / Speed.FromMetersPerSecond(3); Assert.Equal(force, Force.FromNewtons(5)); } [Fact] public void PowerDividedByTorqueEqualsRotationalSpeed() { - var rotationalSpeed = Power.FromWatts(15.0) / Torque.FromNewtonMeters(3); + RotationalSpeed rotationalSpeed = Power.FromWatts(15.0) / Torque.FromNewtonMeters(3); Assert.Equal(rotationalSpeed, RotationalSpeed.FromRadiansPerSecond(5)); } - [Fact] - public void PowerTimesBrakeSpecificFuelConsumptionEqualsMassFlow() - { - var massFlow = Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0) * BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0); - AssertEx.EqualTolerance(massFlow.TonnesPerDay, 20.0, 1e-11); - } - [Fact] public void PowerTimesDurationEqualsEnergy() { - var energy = Power.FromWatts(5.0) * Duration.FromSeconds(8.0); + Energy energy = Power.FromWatts(5.0) * Duration.FromSeconds(8.0); Assert.Equal(energy, Energy.FromJoules(40.0)); } [Fact] public void PowerTimesTimeSpanEqualsEnergy() { - var energy = Power.FromWatts(5.0) * TimeSpan.FromSeconds(8.0); + Energy energy = Power.FromWatts(5.0) * TimeSpan.FromSeconds(8.0); Assert.Equal(energy, Energy.FromJoules(40.0)); } [Fact] public void TimeSpanTimesPowerEqualsEnergy() { - var energy = TimeSpan.FromSeconds(8.0) * Power.FromWatts(5.0); + Energy energy = TimeSpan.FromSeconds(8.0) * Power.FromWatts(5.0); Assert.Equal(energy, Energy.FromJoules(40.0)); } + + [Fact] + public void PowerTimesBrakeSpecificFuelConsumptionEqualsMassFlow() + { + MassFlow massFlow = Power.FromKilowatts(20.0 / 24.0 * 1e6 / 180.0) * BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(180.0); + AssertEx.EqualTolerance(massFlow.TonnesPerDay, 20.0, 1e-11); + } + + [Fact] + public void PowerDividedByMassFlowEqualsSpecificEnergy() + { + SpecificEnergy specificEnergy = Power.FromWatts(15.0) / MassFlow.FromKilogramsPerSecond(3); + Assert.Equal(specificEnergy, SpecificEnergy.FromJoulesPerKilogram(5)); + } + + [Fact] + public void PowerDividedBySpecificEnergyEqualsMassFlow() + { + MassFlow massFlow = Power.FromWatts(15.0) / SpecificEnergy.FromJoulesPerKilogram(3); + Assert.Equal(massFlow, MassFlow.FromKilogramsPerSecond(5)); + } } } diff --git a/UnitsNet.Tests/CustomCode/PressureChangeRateTests.cs b/UnitsNet.Tests/CustomCode/PressureChangeRateTests.cs index e0d6baf1e3..fe16b06d88 100644 --- a/UnitsNet.Tests/CustomCode/PressureChangeRateTests.cs +++ b/UnitsNet.Tests/CustomCode/PressureChangeRateTests.cs @@ -5,7 +5,7 @@ namespace UnitsNet.Tests.CustomCode { public class PressureChangeRateTests : PressureChangeRateTestsBase { - protected override double AtmospheresPerSecondInOnePascalPerSecond => 9.8692 * 1E-6; + protected override double AtmospheresPerSecondInOnePascalPerSecond => 9.8692*1E-6; protected override double KilopascalsPerSecondInOnePascalPerSecond => 1e-3; diff --git a/UnitsNet.Tests/CustomCode/RotationalSpeedTests.cs b/UnitsNet.Tests/CustomCode/RotationalSpeedTests.cs index 93db5f818a..e65f9f8f92 100644 --- a/UnitsNet.Tests/CustomCode/RotationalSpeedTests.cs +++ b/UnitsNet.Tests/CustomCode/RotationalSpeedTests.cs @@ -37,28 +37,28 @@ public class RotationalSpeedTests : RotationalSpeedTestsBase [Fact] public void DurationTimesRotationalSpeedEqualsAngle() { - var angle = Duration.FromSeconds(9.0) * RotationalSpeed.FromRadiansPerSecond(10.0); + Angle angle = Duration.FromSeconds(9.0)*RotationalSpeed.FromRadiansPerSecond(10.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } [Fact] public void RotationalSpeedTimesDurationEqualsAngle() { - var angle = RotationalSpeed.FromRadiansPerSecond(10.0) * Duration.FromSeconds(9.0); + Angle angle = RotationalSpeed.FromRadiansPerSecond(10.0)*Duration.FromSeconds(9.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } [Fact] public void RotationalSpeedTimesTimeSpanEqualsAngle() { - var angle = RotationalSpeed.FromRadiansPerSecond(10.0) * TimeSpan.FromSeconds(9.0); + Angle angle = RotationalSpeed.FromRadiansPerSecond(10.0)*TimeSpan.FromSeconds(9.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } [Fact] public void TimeSpanTimesRotationalSpeedEqualsAngle() { - var angle = TimeSpan.FromSeconds(9.0) * RotationalSpeed.FromRadiansPerSecond(10.0); + Angle angle = TimeSpan.FromSeconds(9.0)*RotationalSpeed.FromRadiansPerSecond(10.0); Assert.Equal(angle, Angle.FromRadians(90.0)); } } diff --git a/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs b/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs index d1af883fd5..ce4904b089 100644 --- a/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs +++ b/UnitsNet.Tests/CustomCode/SpecificEnergyTests.cs @@ -18,38 +18,38 @@ public class SpecificEnergyTests : SpecificEnergyTestsBase protected override double MegawattHoursPerKilogramInOneJoulePerKilogram => 2.77777778e-10; [Fact] - public void DoubleDividedBySpecificEnergyEqualsBrakeSpecificFuelConsumption() + public void MassTimesSpecificEnergyEqualsEnergy() { - var bsfc = 2.0 / SpecificEnergy.FromJoulesPerKilogram(4.0); - Assert.Equal(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(0.5), bsfc); + Energy energy = Mass.FromKilograms(20.0)*SpecificEnergy.FromJoulesPerKilogram(10.0); + Assert.Equal(200d, energy.Joules); } [Fact] - public void MassTimesSpecificEnergyEqualsEnergy() + public void SpecificEnergyTimesMassEqualsEnergy() { - var energy = Mass.FromKilograms(20.0) * SpecificEnergy.FromJoulesPerKilogram(10.0); + Energy energy = SpecificEnergy.FromJoulesPerKilogram(10.0)*Mass.FromKilograms(20.0); Assert.Equal(200d, energy.Joules); } [Fact] - public void SpecificEnergyTimesBrakeSpecificFuelConsumptionEqualsEnergy() + public void DoubleDividedBySpecificEnergyEqualsBrakeSpecificFuelConsumption() { - var value = SpecificEnergy.FromJoulesPerKilogram(10.0) * BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0); - Assert.Equal(200d, value); + BrakeSpecificFuelConsumption bsfc = 2.0 / SpecificEnergy.FromJoulesPerKilogram(4.0); + Assert.Equal(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(0.5), bsfc); } [Fact] - public void SpecificEnergyTimesMassEqualsEnergy() + public void SpecificEnergyTimesMassFlowEqualsPower() { - var energy = SpecificEnergy.FromJoulesPerKilogram(10.0) * Mass.FromKilograms(20.0); - Assert.Equal(200d, energy.Joules); + Power power = SpecificEnergy.FromJoulesPerKilogram(10.0) * MassFlow.FromKilogramsPerSecond(20.0); + Assert.Equal(200d, power.Watts); } [Fact] - public void SpecificEnergyTimesMassFlowEqualsPower() + public void SpecificEnergyTimesBrakeSpecificFuelConsumptionEqualsEnergy() { - var power = SpecificEnergy.FromJoulesPerKilogram(10.0) * MassFlow.FromKilogramsPerSecond(20.0); - Assert.Equal(200d, power.Watts); + double value = SpecificEnergy.FromJoulesPerKilogram(10.0) * BrakeSpecificFuelConsumption.FromKilogramsPerJoule(20.0); + Assert.Equal(200d, value); } } } diff --git a/UnitsNet.Tests/CustomCode/SpecificWeightTests.cs b/UnitsNet.Tests/CustomCode/SpecificWeightTests.cs index 541ca69b25..ca86cd7f5e 100644 --- a/UnitsNet.Tests/CustomCode/SpecificWeightTests.cs +++ b/UnitsNet.Tests/CustomCode/SpecificWeightTests.cs @@ -42,24 +42,24 @@ public class SpecificWeightTests : SpecificWeightTestsBase protected override double MeganewtonsPerCubicMeterInOneNewtonPerCubicMeter => 1e-6; [Fact] - public void SpecificWeightDividedByAccelerationEqualsDensity() + public void SpecificWeightTimesLengthEqualsPressure() { - var density = SpecificWeight.FromNewtonsPerCubicMeter(20) / Acceleration.FromMetersPerSecondSquared(2); - Assert.Equal(Density.FromKilogramsPerCubicMeter(10), density); + Pressure pressure = SpecificWeight.FromNewtonsPerCubicMeter(10) * Length.FromMeters(2); + Assert.Equal(Pressure.FromPascals(20), pressure); } [Fact] public void SpecificWeightDividedByDensityEqualsAcceleration() { - var acceleration = SpecificWeight.FromNewtonsPerCubicMeter(40) / Density.FromKilogramsPerCubicMeter(4); + Acceleration acceleration = SpecificWeight.FromNewtonsPerCubicMeter(40) / Density.FromKilogramsPerCubicMeter(4); Assert.Equal(Acceleration.FromMetersPerSecondSquared(10), acceleration); } [Fact] - public void SpecificWeightTimesLengthEqualsPressure() + public void SpecificWeightDividedByAccelerationEqualsDensity() { - var pressure = SpecificWeight.FromNewtonsPerCubicMeter(10) * Length.FromMeters(2); - Assert.Equal(Pressure.FromPascals(20), pressure); + Density density = SpecificWeight.FromNewtonsPerCubicMeter(20) / Acceleration.FromMetersPerSecondSquared(2); + Assert.Equal(Density.FromKilogramsPerCubicMeter(10), density); } } } diff --git a/UnitsNet.Tests/CustomCode/SpeedTests.cs b/UnitsNet.Tests/CustomCode/SpeedTests.cs index 98dd17bde7..cc96ce9c80 100644 --- a/UnitsNet.Tests/CustomCode/SpeedTests.cs +++ b/UnitsNet.Tests/CustomCode/SpeedTests.cs @@ -75,63 +75,63 @@ public class SpeedTests : SpeedTestsBase [Fact] public void DurationSpeedTimesEqualsLength() { - var length = Duration.FromSeconds(2) * Speed.FromMetersPerSecond(20); + Length length = Duration.FromSeconds(2)*Speed.FromMetersPerSecond(20); Assert.Equal(length, Length.FromMeters(40)); } [Fact] public void LengthDividedByDurationEqualsSpeed() { - var speed = Length.FromMeters(20) / Duration.FromSeconds(2); + Speed speed = Length.FromMeters(20)/Duration.FromSeconds(2); Assert.Equal(speed, Speed.FromMetersPerSecond(10)); } [Fact] public void LengthDividedByTimeSpanEqualsSpeed() { - var speed = Length.FromMeters(20) / TimeSpan.FromSeconds(2); + Speed speed = Length.FromMeters(20)/TimeSpan.FromSeconds(2); Assert.Equal(speed, Speed.FromMetersPerSecond(10)); } [Fact] public void SpeedDividedByDurationEqualsAcceleration() { - var acceleration = Speed.FromMetersPerSecond(20) / Duration.FromSeconds(2); + Acceleration acceleration = Speed.FromMetersPerSecond(20)/Duration.FromSeconds(2); Assert.Equal(acceleration, Acceleration.FromMetersPerSecondSquared(10)); } [Fact] public void SpeedDividedByTimeSpanEqualsAcceleration() { - var acceleration = Speed.FromMetersPerSecond(20) / TimeSpan.FromSeconds(2); + Acceleration acceleration = Speed.FromMetersPerSecond(20)/TimeSpan.FromSeconds(2); Assert.Equal(acceleration, Acceleration.FromMetersPerSecondSquared(10)); } [Fact] - public void SpeedTimesAreaEqualsVolumeFlow() + public void SpeedTimesDurationEqualsLength() { - var volumeFlow = Speed.FromMetersPerSecond(2) * Area.FromSquareMeters(20); - Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(40), volumeFlow); + Length length = Speed.FromMetersPerSecond(20)*Duration.FromSeconds(2); + Assert.Equal(length, Length.FromMeters(40)); } [Fact] - public void SpeedTimesDensityEqualsMassFlux() + public void SpeedTimesTimeSpanEqualsLength() { - var massFlux = Speed.FromMetersPerSecond(20) * Density.FromKilogramsPerCubicMeter(2); - Assert.Equal(massFlux, MassFlux.FromKilogramsPerSecondPerSquareMeter(40)); + Length length = Speed.FromMetersPerSecond(20)*TimeSpan.FromSeconds(2); + Assert.Equal(length, Length.FromMeters(40)); } [Fact] - public void SpeedTimesDurationEqualsLength() + public void TimeSpanTimesSpeedEqualsLength() { - var length = Speed.FromMetersPerSecond(20) * Duration.FromSeconds(2); + Length length = TimeSpan.FromSeconds(2)*Speed.FromMetersPerSecond(20); Assert.Equal(length, Length.FromMeters(40)); } [Fact] public void SpeedTimesLengthEqualsKinematicViscosity() { - var kinematicViscosity = Length.FromMeters(20) * Speed.FromMetersPerSecond(2); + KinematicViscosity kinematicViscosity = Length.FromMeters(20) * Speed.FromMetersPerSecond(2); Assert.Equal(KinematicViscosity.FromSquareMetersPerSecond(40), kinematicViscosity); } @@ -139,22 +139,22 @@ public void SpeedTimesLengthEqualsKinematicViscosity() public void SpeedTimesSpeedEqualsSpecificEnergy() { //m^2/s^2 = kg*m*m/(s^2*kg) = J/kg - var length = Speed.FromMetersPerSecond(2) * Speed.FromMetersPerSecond(20); + SpecificEnergy length = Speed.FromMetersPerSecond(2) * Speed.FromMetersPerSecond(20); Assert.Equal(length, SpecificEnergy.FromJoulesPerKilogram(40)); } [Fact] - public void SpeedTimesTimeSpanEqualsLength() + public void SpeedTimesDensityEqualsMassFlux() { - var length = Speed.FromMetersPerSecond(20) * TimeSpan.FromSeconds(2); - Assert.Equal(length, Length.FromMeters(40)); + MassFlux massFlux = Speed.FromMetersPerSecond(20) * Density.FromKilogramsPerCubicMeter(2); + Assert.Equal(massFlux, MassFlux.FromKilogramsPerSecondPerSquareMeter(40)); } [Fact] - public void TimeSpanTimesSpeedEqualsLength() + public void SpeedTimesAreaEqualsVolumeFlow() { - var length = TimeSpan.FromSeconds(2) * Speed.FromMetersPerSecond(20); - Assert.Equal(length, Length.FromMeters(40)); + VolumeFlow volumeFlow = Speed.FromMetersPerSecond(2) * Area.FromSquareMeters(20); + Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(40), volumeFlow); } } } diff --git a/UnitsNet.Tests/CustomCode/StonePoundsTests.cs b/UnitsNet.Tests/CustomCode/StonePoundsTests.cs index 2b1bafc13d..b8cafbb920 100644 --- a/UnitsNet.Tests/CustomCode/StonePoundsTests.cs +++ b/UnitsNet.Tests/CustomCode/StonePoundsTests.cs @@ -13,32 +13,19 @@ public class StonePoundsTests private const double StoneTolerance = 1e-4; private const double PoundsTolerance = 1e-4; - // These cultures use a thin space in digit grouping - [Theory] - [InlineData("nn-NO")] - [InlineData("fr-FR")] - public void StonePoundsToString_GivenCultureWithThinSpaceDigitGroup_ReturnsNumberWithThinSpaceDigitGroup(string cultureName) - { - var formatProvider = new CultureInfo(cultureName); - var m = Mass.FromStonePounds(3500, 1); - var stonePounds = m.StonePounds; - - Assert.Equal("3 500 st 1 lb", stonePounds.ToString(formatProvider)); - } - [Fact] public void StonePoundsFrom() { - var m = Mass.FromStonePounds(2, 3); - var expectedKg = 2 / StoneInOneKilogram + 3 / PoundsInOneKilogram; + Mass m = Mass.FromStonePounds(2, 3); + double expectedKg = 2/StoneInOneKilogram + 3/PoundsInOneKilogram; AssertEx.EqualTolerance(expectedKg, m.Kilograms, StoneTolerance); } [Fact] public void StonePoundsRoundTrip() { - var m = Mass.FromStonePounds(2, 3); - var stonePounds = m.StonePounds; + Mass m = Mass.FromStonePounds(2, 3); + StonePounds stonePounds = m.StonePounds; AssertEx.EqualTolerance(2, stonePounds.Stone, StoneTolerance); AssertEx.EqualTolerance(3, stonePounds.Pounds, PoundsTolerance); } @@ -46,11 +33,24 @@ public void StonePoundsRoundTrip() [Fact] public void StonePoundsToString_FormatsNumberInDefaultCulture() { - var m = Mass.FromStonePounds(3500, 1); - var stonePounds = m.StonePounds; - var numberInCurrentCulture = 3500.ToString("n0", CultureInfo.CurrentUICulture); // Varies between machines, can't hard code it + Mass m = Mass.FromStonePounds(3500, 1); + StonePounds stonePounds = m.StonePounds; + string numberInCurrentCulture = 3500.ToString("n0", CultureInfo.CurrentUICulture); // Varies between machines, can't hard code it Assert.Equal($"{numberInCurrentCulture} st 1 lb", stonePounds.ToString()); } + + // These cultures use a thin space in digit grouping + [Theory] + [InlineData("nn-NO")] + [InlineData("fr-FR")] + public void StonePoundsToString_GivenCultureWithThinSpaceDigitGroup_ReturnsNumberWithThinSpaceDigitGroup(string cultureName) + { + var formatProvider = new CultureInfo(cultureName); + Mass m = Mass.FromStonePounds(3500, 1); + StonePounds stonePounds = m.StonePounds; + + Assert.Equal("3 500 st 1 lb", stonePounds.ToString(formatProvider)); + } } } diff --git a/UnitsNet.Tests/CustomCode/TemperatureChangeRateTests.cs b/UnitsNet.Tests/CustomCode/TemperatureChangeRateTests.cs index f7f3938afa..17f17a8201 100644 --- a/UnitsNet.Tests/CustomCode/TemperatureChangeRateTests.cs +++ b/UnitsNet.Tests/CustomCode/TemperatureChangeRateTests.cs @@ -23,6 +23,6 @@ public class TemperatureChangeRateTests : TemperatureChangeRateTestsBase protected override double NanodegreesCelsiusPerSecondInOneDegreeCelsiusPerSecond => 1E9; - protected override double DegreesCelsiusPerMinuteInOneDegreeCelsiusPerSecond => 60; + protected override double DegreesCelsiusPerMinuteInOneDegreeCelsiusPerSecond => 60; } } diff --git a/UnitsNet.Tests/CustomCode/TemperatureTests.cs b/UnitsNet.Tests/CustomCode/TemperatureTests.cs index 1a7285258b..05b0cf511d 100644 --- a/UnitsNet.Tests/CustomCode/TemperatureTests.cs +++ b/UnitsNet.Tests/CustomCode/TemperatureTests.cs @@ -30,56 +30,12 @@ public class TemperatureTests : TemperatureTestsBase public static IEnumerable DividedByTemperatureDeltaEqualsTemperatureData { get; } = new List { - new object[] {Temperature.FromDegreesCelsius(10), 1, Temperature.FromDegreesCelsius(10)}, - new object[] {Temperature.FromDegreesCelsius(10), 5, Temperature.FromDegreesCelsius(2)}, - new object[] {Temperature.FromDegreesCelsius(10), -10, Temperature.FromDegreesCelsius(-1)}, - new object[] {Temperature.FromDegreesFahrenheit(10), 1, Temperature.FromDegreesFahrenheit(10)}, - new object[] {Temperature.FromDegreesFahrenheit(10), 5, Temperature.FromDegreesFahrenheit(2)}, - new object[] {Temperature.FromDegreesFahrenheit(10), -10, Temperature.FromDegreesFahrenheit(-1)} - }; - - public static IEnumerable MultiplyByTemperatureDeltaEqualsTemperatureData { get; } = - new List - { - new object[] {Temperature.FromDegreesCelsius(10), 0, Temperature.FromDegreesCelsius(0)}, - new object[] {Temperature.FromDegreesCelsius(10), 5, Temperature.FromDegreesCelsius(50)}, - new object[] {Temperature.FromDegreesCelsius(10), -5, Temperature.FromDegreesCelsius(-50)}, - new object[] {Temperature.FromDegreesFahrenheit(10), 0, Temperature.FromDegreesFahrenheit(0)}, - new object[] {Temperature.FromDegreesFahrenheit(10), 5, Temperature.FromDegreesFahrenheit(50)}, - new object[] {Temperature.FromDegreesFahrenheit(10), -5, Temperature.FromDegreesFahrenheit(-50)} - }; - - public static IEnumerable TemperatureDeltaPlusTemperatureEqualsTemperatureData { get; } = - new List - { - new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(0), Temperature.FromDegreesCelsius(-10)}, - new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(0)}, - new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(10)}, - new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(0), Temperature.FromDegreesFahrenheit(-10)}, - new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(0)}, - new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10)} - }; - - public static IEnumerable TemperatureMinusTemperatureDeltaEqualsTemperatureData { get; } = - new List - { - new object[] {Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(10)}, - new object[] {Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(0)}, - new object[] {Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(30), Temperature.FromDegreesCelsius(-10)}, - new object[] {Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(10)}, - new object[] {Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(0)}, - new object[] {Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(30), Temperature.FromDegreesFahrenheit(-10)} - }; - - public static IEnumerable TemperaturePlusTemperatureDeltaEqualsTemperatureData { get; } = - new List - { - new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(0), Temperature.FromDegreesCelsius(-10)}, - new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(0)}, - new object[] {Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(10)}, - new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(0), Temperature.FromDegreesFahrenheit(-10)}, - new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(0)}, - new object[] {Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10)} + new object[] { Temperature.FromDegreesCelsius(10), 1, Temperature.FromDegreesCelsius(10) }, + new object[] { Temperature.FromDegreesCelsius(10), 5, Temperature.FromDegreesCelsius(2) }, + new object[] { Temperature.FromDegreesCelsius(10), -10, Temperature.FromDegreesCelsius(-1) }, + new object[] { Temperature.FromDegreesFahrenheit(10), 1, Temperature.FromDegreesFahrenheit(10) }, + new object[] { Temperature.FromDegreesFahrenheit(10), 5, Temperature.FromDegreesFahrenheit(2) }, + new object[] { Temperature.FromDegreesFahrenheit(10), -10, Temperature.FromDegreesFahrenheit(-1) } }; [SuppressMessage("ReSharper", "ImpureMethodCallOnReadonlyValueField", @@ -88,42 +44,87 @@ public class TemperatureTests : TemperatureTestsBase [MemberData(nameof(DividedByTemperatureDeltaEqualsTemperatureData))] public void DividedByTemperatureDeltaEqualsTemperature(Temperature temperature, int divisor, Temperature expected) { - var resultTemp = temperature.Divide(divisor, temperature.Unit); + Temperature resultTemp = temperature.Divide(divisor, temperature.Unit); Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); } + public static IEnumerable MultiplyByTemperatureDeltaEqualsTemperatureData { get; } = + new List + { + new object[] { Temperature.FromDegreesCelsius(10), 0, Temperature.FromDegreesCelsius(0) }, + new object[] { Temperature.FromDegreesCelsius(10), 5, Temperature.FromDegreesCelsius(50) }, + new object[] { Temperature.FromDegreesCelsius(10), -5, Temperature.FromDegreesCelsius(-50) }, + new object[] { Temperature.FromDegreesFahrenheit(10), 0, Temperature.FromDegreesFahrenheit(0) }, + new object[] { Temperature.FromDegreesFahrenheit(10), 5, Temperature.FromDegreesFahrenheit(50) }, + new object[] { Temperature.FromDegreesFahrenheit(10), -5, Temperature.FromDegreesFahrenheit(-50) } + }; + [SuppressMessage("ReSharper", "ImpureMethodCallOnReadonlyValueField", Justification = "R# incorrectly identifies method as impure, due to internal method calls.")] [Theory] [MemberData(nameof(MultiplyByTemperatureDeltaEqualsTemperatureData))] public void MultiplyByTemperatureDeltaEqualsTemperature(Temperature temperature, int factor, Temperature expected) { - var resultTemp = temperature.Multiply(factor, temperature.Unit); + Temperature resultTemp = temperature.Multiply(factor, temperature.Unit); Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); } + public static IEnumerable TemperatureDeltaPlusTemperatureEqualsTemperatureData { get; } = + new List + { + new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(0), Temperature.FromDegreesCelsius(-10) }, + new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(0) }, + new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(10) }, + new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(0), Temperature.FromDegreesFahrenheit(-10) }, + new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(0) }, + new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10) } + }; + [Theory] [MemberData(nameof(TemperatureDeltaPlusTemperatureEqualsTemperatureData))] public void TemperatureDeltaPlusTemperatureEqualsTemperature(Temperature temperature, TemperatureDelta delta, Temperature expected) { - var resultTemp = delta + temperature; + Temperature resultTemp = delta + temperature; Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); } + public static IEnumerable TemperatureMinusTemperatureDeltaEqualsTemperatureData { get; } = + new List + { + new object[] { Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(10) }, + new object[] { Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(0) }, + new object[] { Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(30), Temperature.FromDegreesCelsius(-10) }, + new object[] { Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(10) }, + new object[] { Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(0) }, + new object[] { Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(30), Temperature.FromDegreesFahrenheit(-10) } + }; + [Theory] [MemberData(nameof(TemperatureMinusTemperatureDeltaEqualsTemperatureData))] public void TemperatureMinusTemperatureDeltaEqualsTemperature(Temperature temperature, TemperatureDelta delta, Temperature expected) { - var resultTemp = temperature - delta; + Temperature resultTemp = temperature - delta; Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); } + public static IEnumerable TemperaturePlusTemperatureDeltaEqualsTemperatureData { get; } = + new List + { + new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(0), Temperature.FromDegreesCelsius(-10) }, + new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(0) }, + new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(10) }, + new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(0), Temperature.FromDegreesFahrenheit(-10) }, + new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(0) }, + new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10) } + }; + + [Theory] [MemberData(nameof(TemperaturePlusTemperatureDeltaEqualsTemperatureData))] public void TemperaturePlusTemperatureDeltaEqualsTemperature(Temperature temperature, TemperatureDelta delta, Temperature expected) { - var resultTemp = temperature + delta; + Temperature resultTemp = temperature + delta; Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); } } diff --git a/UnitsNet.Tests/CustomCode/TorqueTests.cs b/UnitsNet.Tests/CustomCode/TorqueTests.cs index a60df46868..aef7961cb1 100644 --- a/UnitsNet.Tests/CustomCode/TorqueTests.cs +++ b/UnitsNet.Tests/CustomCode/TorqueTests.cs @@ -52,14 +52,14 @@ public class TorqueTests : TorqueTestsBase [Fact] public void TorqueDividedByForceEqualsLength() { - var length = Torque.FromNewtonMeters(4) / Force.FromNewtons(2); + Length length = Torque.FromNewtonMeters(4)/Force.FromNewtons(2); Assert.Equal(length, Length.FromMeters(2)); } [Fact] public void TorqueDividedByLengthEqualsForce() { - var force = Torque.FromNewtonMeters(4) / Length.FromMeters(2); + Force force = Torque.FromNewtonMeters(4)/Length.FromMeters(2); Assert.Equal(force, Force.FromNewtons(2)); } } diff --git a/UnitsNet.Tests/CustomCode/VolumeTests.cs b/UnitsNet.Tests/CustomCode/VolumeTests.cs index c459ecb911..ad6c2dca04 100644 --- a/UnitsNet.Tests/CustomCode/VolumeTests.cs +++ b/UnitsNet.Tests/CustomCode/VolumeTests.cs @@ -94,48 +94,48 @@ public class VolumeTests : VolumeTestsBase protected override double ImperialPintsInOneCubicMeter => 1.7597539863927023e3; - [Theory] - [InlineData(20, 2, 10)] - [InlineData(20, 80, 0.25)] - public void VolumeDividedByTimeSpanEqualsVolumeFlow(double cubicMeters, double seconds, double expectedCubicMetersPerSecond) + [ Fact] + public void VolumeDividedByAreaEqualsLength() { - var volumeFlow = Volume.FromCubicMeters(cubicMeters) / TimeSpan.FromSeconds(seconds); - Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(expectedCubicMetersPerSecond), volumeFlow); + Length length = Volume.FromCubicMeters(15)/Area.FromSquareMeters(5); + Assert.Equal(length, Length.FromMeters(3)); } [Fact] - public void VolumeDividedByAreaEqualsLength() + public void VolumeDividedByLengthEqualsArea() { - var length = Volume.FromCubicMeters(15) / Area.FromSquareMeters(5); - Assert.Equal(length, Length.FromMeters(3)); + Area area = Volume.FromCubicMeters(15)/Length.FromMeters(5); + Assert.Equal(area, Area.FromSquareMeters(3)); } [Fact] - public void VolumeDividedByDurationEqualsVolumeFlow() + public void VolumeTimesDensityEqualsMass() { - var volumeFlow = Volume.FromCubicMeters(20) / Duration.FromSeconds(2); - Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(10), volumeFlow); + Mass mass = Volume.FromCubicMeters(2)*Density.FromKilogramsPerCubicMeter(3); + Assert.Equal(mass, Mass.FromKilograms(6)); } - [Fact] - public void VolumeDividedByLengthEqualsArea() + [Theory] + [InlineData(20, 2, 10)] + [InlineData(20, 80, 0.25)] + public void VolumeDividedByTimeSpanEqualsVolumeFlow(double cubicMeters, double seconds, double expectedCubicMetersPerSecond) { - var area = Volume.FromCubicMeters(15) / Length.FromMeters(5); - Assert.Equal(area, Area.FromSquareMeters(3)); + VolumeFlow volumeFlow = Volume.FromCubicMeters(cubicMeters) / TimeSpan.FromSeconds(seconds); + Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(expectedCubicMetersPerSecond), volumeFlow); } [Fact] - public void VolumeDividedByVolumeFlowEqualsTimeSpan() + public void VolumeDividedByDurationEqualsVolumeFlow() { - var timeSpan = Volume.FromCubicMeters(20) / VolumeFlow.FromCubicMetersPerSecond(2); - Assert.Equal(TimeSpan.FromSeconds(10), timeSpan); + VolumeFlow volumeFlow = Volume.FromCubicMeters(20) / Duration.FromSeconds(2); + Assert.Equal(VolumeFlow.FromCubicMetersPerSecond(10), volumeFlow); } [Fact] - public void VolumeTimesDensityEqualsMass() + public void VolumeDividedByVolumeFlowEqualsTimeSpan() { - var mass = Volume.FromCubicMeters(2) * Density.FromKilogramsPerCubicMeter(3); - Assert.Equal(mass, Mass.FromKilograms(6)); + TimeSpan timeSpan = Volume.FromCubicMeters(20) / VolumeFlow.FromCubicMetersPerSecond(2); + Assert.Equal(TimeSpan.FromSeconds(10), timeSpan); } } } diff --git a/UnitsNet.Tests/CustomQuantities/HowMuch.cs b/UnitsNet.Tests/CustomQuantities/HowMuch.cs index e7bc7a3d76..5f6bab3543 100644 --- a/UnitsNet.Tests/CustomQuantities/HowMuch.cs +++ b/UnitsNet.Tests/CustomQuantities/HowMuch.cs @@ -1,13 +1,10 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - using System; namespace UnitsNet.Tests.CustomQuantities { - /// + /// /// - /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. + /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. /// public struct HowMuch : IQuantity { @@ -30,8 +27,9 @@ public HowMuch(double value, Enum unit) : this() public QuantityInfo QuantityInfo => new QuantityInfo(Type, new UnitInfo[] { - new UnitInfo(HowMuchUnit.Some, BaseUnits.Undefined), new UnitInfo(HowMuchUnit.ATon, BaseUnits.Undefined), - new UnitInfo(HowMuchUnit.AShitTon, BaseUnits.Undefined) + new UnitInfo(HowMuchUnit.Some, BaseUnits.Undefined), + new UnitInfo(HowMuchUnit.ATon, BaseUnits.Undefined), + new UnitInfo(HowMuchUnit.AShitTon, BaseUnits.Undefined), }, HowMuchUnit.Some, Zero, diff --git a/UnitsNet.Tests/CustomQuantities/HowMuchUnit.cs b/UnitsNet.Tests/CustomQuantities/HowMuchUnit.cs index a5aa6ee7c3..c58f9fc548 100644 --- a/UnitsNet.Tests/CustomQuantities/HowMuchUnit.cs +++ b/UnitsNet.Tests/CustomQuantities/HowMuchUnit.cs @@ -1,10 +1,7 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - namespace UnitsNet.Tests.CustomQuantities { /// - /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. + /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. /// public enum HowMuchUnit { diff --git a/UnitsNet.Tests/DecimalOverloadTests.cs b/UnitsNet.Tests/DecimalOverloadTests.cs index 3740629a21..841c9b162b 100644 --- a/UnitsNet.Tests/DecimalOverloadTests.cs +++ b/UnitsNet.Tests/DecimalOverloadTests.cs @@ -8,17 +8,17 @@ namespace UnitsNet.Tests public class DecimalOverloadTests { [Fact] - public static void CreatingQuantityWithDecimalBackingFieldFromDecimalReturnsCorrectValue() + public static void CreatingQuantityWithDoubleBackingFieldFromDecimalReturnsCorrectValue() { - var power = Power.FromWatts(1m); - Assert.Equal(1.0, power.Watts); + Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(1m); + Assert.Equal(1.0, acceleration.MetersPerSecondSquared); } [Fact] - public static void CreatingQuantityWithDoubleBackingFieldFromDecimalReturnsCorrectValue() + public static void CreatingQuantityWithDecimalBackingFieldFromDecimalReturnsCorrectValue() { - var acceleration = Acceleration.FromMetersPerSecondSquared(1m); - Assert.Equal(1.0, acceleration.MetersPerSecondSquared); + Power power = Power.FromWatts(1m); + Assert.Equal(1.0, power.Watts); } } } diff --git a/UnitsNet.Tests/DummyIQuantity.cs b/UnitsNet.Tests/DummyIQuantity.cs index 52a6de8d0f..04f97a7ea2 100644 --- a/UnitsNet.Tests/DummyIQuantity.cs +++ b/UnitsNet.Tests/DummyIQuantity.cs @@ -1,7 +1,6 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; +using System.Collections.Generic; +using System.Text; using JetBrains.Annotations; namespace UnitsNet.Tests diff --git a/UnitsNet.Tests/EnumUtils.cs b/UnitsNet.Tests/EnumUtils.cs index dc49cce56e..305b92a1c6 100644 --- a/UnitsNet.Tests/EnumUtils.cs +++ b/UnitsNet.Tests/EnumUtils.cs @@ -10,7 +10,7 @@ public static class EnumUtils { public static T[] GetEnumValues() { - return Enum.GetValues(typeof(T)).Cast().ToArray(); + return Enum.GetValues(typeof (T)).Cast().ToArray(); } } } diff --git a/UnitsNet.Tests/GeneratedQuantityCodeTests.cs b/UnitsNet.Tests/GeneratedQuantityCodeTests.cs index d4b7901b21..4f188897f4 100644 --- a/UnitsNet.Tests/GeneratedQuantityCodeTests.cs +++ b/UnitsNet.Tests/GeneratedQuantityCodeTests.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using Xunit; +using Xunit; namespace UnitsNet.Tests { @@ -24,13 +21,11 @@ public void LengthEquals_GivenMaxError_ReturnsTrueIfWithinError() var smallError = 1e-5; Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), 0, ComparisonType.Relative), "Integer values have zero difference."); - Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), smallError, ComparisonType.Relative), - "Using a max difference value should not change that fact."); + Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), smallError, ComparisonType.Relative), "Using a max difference value should not change that fact."); Assert.False(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), 0, ComparisonType.Relative), "Example of floating precision arithmetic that produces slightly different results."); - Assert.True(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), smallError, ComparisonType.Relative), - "But the difference is very small"); + Assert.True(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), smallError, ComparisonType.Relative), "But the difference is very small"); } } } diff --git a/UnitsNet.Tests/Helpers/TypeDescriptorContext.cs b/UnitsNet.Tests/Helpers/TypeDescriptorContext.cs index 7ef72c614e..28e1979d88 100644 --- a/UnitsNet.Tests/Helpers/TypeDescriptorContext.cs +++ b/UnitsNet.Tests/Helpers/TypeDescriptorContext.cs @@ -2,45 +2,22 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.ComponentModel; +using System.Text; namespace UnitsNet.Tests.Helpers { /// - /// Is used to imitate e property with attributes + /// Is used to imitate e property with attributes /// public class TypeDescriptorContext : ITypeDescriptorContext { - public TypeDescriptorContext(string name, Attribute[] attributes) - { - PropertyDescriptor = new PropertyDescriptor_(name, attributes); - } - - public IContainer Container => throw new NotImplementedException(); - - public object Instance => throw new NotImplementedException(); - - public PropertyDescriptor PropertyDescriptor { get; set; } - - public object GetService(Type serviceType) - { - throw new NotImplementedException(); - } - - public void OnComponentChanged() - { - throw new NotImplementedException(); - } - - public bool OnComponentChanging() - { - throw new NotImplementedException(); - } - public class PropertyDescriptor_ : PropertyDescriptor { public PropertyDescriptor_(string name, Attribute[] attributes) : base(name, attributes) { + } public override Type ComponentType => throw new NotImplementedException(); @@ -74,5 +51,31 @@ public override bool ShouldSerializeValue(object component) throw new NotImplementedException(); } } + + public TypeDescriptorContext(string name, Attribute[] attributes) + { + PropertyDescriptor = new PropertyDescriptor_(name, attributes); + } + + public IContainer Container => throw new NotImplementedException(); + + public object Instance => throw new NotImplementedException(); + + public PropertyDescriptor PropertyDescriptor { get; set; } + + public object GetService(Type serviceType) + { + throw new NotImplementedException(); + } + + public void OnComponentChanged() + { + throw new NotImplementedException(); + } + + public bool OnComponentChanging() + { + throw new NotImplementedException(); + } } } diff --git a/UnitsNet.Tests/IntOverloadTests.cs b/UnitsNet.Tests/IntOverloadTests.cs index 8cb75efa61..bf63007ba7 100644 --- a/UnitsNet.Tests/IntOverloadTests.cs +++ b/UnitsNet.Tests/IntOverloadTests.cs @@ -10,14 +10,14 @@ public class IntOverloadTests [Fact] public static void CreatingQuantityWithDoubleBackingFieldFromIntReturnsCorrectValue() { - var acceleration = Acceleration.FromMetersPerSecondSquared(1); + Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(1); Assert.Equal(1.0, acceleration.MetersPerSecondSquared); } [Fact] public static void CreatingQuantityWithIntBackingFieldFromIntReturnsCorrectValue() { - var power = Power.FromWatts(1); + Power power = Power.FromWatts(1); Assert.Equal(1.0, power.Watts); } } diff --git a/UnitsNet.Tests/InterUnitConversionTests.cs b/UnitsNet.Tests/InterUnitConversionTests.cs index cf8a89ef6d..d19bd70de0 100644 --- a/UnitsNet.Tests/InterUnitConversionTests.cs +++ b/UnitsNet.Tests/InterUnitConversionTests.cs @@ -10,16 +10,16 @@ public class InterUnitConversionTests [Fact] public void KilogramForceToKilogram() { - var force = Force.FromKilogramsForce(1); - var mass = Mass.FromGravitationalForce(force); + Force force = Force.FromKilogramsForce(1); + Mass mass = Mass.FromGravitationalForce(force); Assert.Equal(mass.Kilograms, force.KilogramsForce); } [Fact] public void KilogramToKilogramForce() { - var mass = Mass.FromKilograms(1); - var force = Force.FromKilogramsForce(mass.Kilograms); + Mass mass = Mass.FromKilograms(1); + Force force = Force.FromKilogramsForce(mass.Kilograms); Assert.Equal(mass.Kilograms, force.KilogramsForce); } } diff --git a/UnitsNet.Tests/LongOverloadTests.cs b/UnitsNet.Tests/LongOverloadTests.cs index c310c7209e..fd54377f08 100644 --- a/UnitsNet.Tests/LongOverloadTests.cs +++ b/UnitsNet.Tests/LongOverloadTests.cs @@ -10,14 +10,14 @@ public class LongOverloadTests [Fact] public static void CreatingQuantityWithDoubleBackingFieldFromLongReturnsCorrectValue() { - var acceleration = Acceleration.FromMetersPerSecondSquared(1L); + Acceleration acceleration = Acceleration.FromMetersPerSecondSquared(1L); Assert.Equal(1.0, acceleration.MetersPerSecondSquared); } [Fact] public static void CreatingQuantityWithLongBackingFieldFromLongReturnsCorrectValue() { - var power = Power.FromWatts(1L); + Power power = Power.FromWatts(1L); Assert.Equal(1.0, power.Watts); } } diff --git a/UnitsNet.Tests/QuantityIConvertibleTests.cs b/UnitsNet.Tests/QuantityIConvertibleTests.cs index a55910af3f..698d4ce9b9 100644 --- a/UnitsNet.Tests/QuantityIConvertibleTests.cs +++ b/UnitsNet.Tests/QuantityIConvertibleTests.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; using System.Globalization; using UnitsNet.Units; using Xunit; @@ -11,7 +8,7 @@ namespace UnitsNet.Tests public class QuantityIConvertibleTests { private static Length length = Length.FromMeters(3.0); - private static readonly IConvertible lengthAsIConvertible = Length.FromMeters(3.0); + private static IConvertible lengthAsIConvertible = Length.FromMeters(3.0); [Fact] public void GetTypeCodeTest() @@ -65,7 +62,7 @@ public void ToDecimalTest() [Fact] public void ToDoubleTest() { - var expected = 3.0; + double expected = 3.0; Assert.Equal(expected, lengthAsIConvertible.ToDouble(null)); Assert.Equal(expected, Convert.ToDouble(length)); Assert.Equal(expected, Convert.ChangeType(length, typeof(double))); @@ -83,7 +80,7 @@ public void ToInt16Test() [Fact] public void ToInt32Test() { - var expected = 3; + int expected = 3; Assert.Equal(expected, lengthAsIConvertible.ToInt32(null)); Assert.Equal(expected, Convert.ToInt32(length)); Assert.Equal(expected, Convert.ChangeType(length, typeof(int))); @@ -119,7 +116,7 @@ public void ToSingleTest() [Fact] public void ToStringTest() { - var expected = length.ToString(CultureInfo.CurrentUICulture); + string expected = length.ToString(CultureInfo.CurrentUICulture); Assert.Equal(expected, lengthAsIConvertible.ToString(CultureInfo.CurrentUICulture)); Assert.Equal(expected, Convert.ToString(length, CultureInfo.CurrentUICulture)); Assert.Equal(expected, Convert.ChangeType(length, typeof(string), CultureInfo.CurrentUICulture)); diff --git a/UnitsNet.Tests/QuantityIFormattableTests.cs b/UnitsNet.Tests/QuantityIFormattableTests.cs index 3e403808b5..059b5b22e2 100644 --- a/UnitsNet.Tests/QuantityIFormattableTests.cs +++ b/UnitsNet.Tests/QuantityIFormattableTests.cs @@ -11,17 +11,17 @@ public class QuantityIFormattableTests { private static Length length = Length.FromFeet(1.2345678); - [Theory] - [InlineData("s", "1 ft")] - [InlineData("s1", "1.2 ft")] - [InlineData("s2", "1.23 ft")] - [InlineData("s3", "1.235 ft")] - [InlineData("s4", "1.2346 ft")] - [InlineData("s5", "1.23457 ft")] - [InlineData("s6", "1.234568 ft")] - public void SFormatEqualsSignificantDigits(string sFormatString, string expected) + [Fact] + public void GFormatStringEqualsToString() { - Assert.Equal(expected, length.ToString(sFormatString, NumberFormatInfo.InvariantInfo)); + Assert.Equal(length.ToString("g"), length.ToString()); + } + + [Fact] + public void EmptyOrNullFormatStringEqualsGFormat() + { + Assert.Equal(length.ToString("g"), length.ToString(string.Empty)); + Assert.Equal(length.ToString("g"), length.ToString((string)null)); } [Fact] @@ -41,22 +41,28 @@ public void AFormatWithInvalidIndexThrowsFormatException() } [Fact] - public void EmptyOrNullFormatStringEqualsGFormat() + public void VFormatEqualsValueToString() { - Assert.Equal(length.ToString("g"), length.ToString(string.Empty)); - Assert.Equal(length.ToString("g"), length.ToString((string) null)); + Assert.Equal(length.Value.ToString(CultureInfo.CurrentUICulture), length.ToString("v")); } [Fact] - public void GFormatStringEqualsToString() + public void QFormatEqualsQuantityName() { - Assert.Equal(length.ToString("g"), length.ToString()); + Assert.Equal(Length.Info.Name, length.ToString("q")); } - [Fact] - public void QFormatEqualsQuantityName() + [Theory] + [InlineData("s", "1 ft")] + [InlineData("s1", "1.2 ft")] + [InlineData("s2", "1.23 ft")] + [InlineData("s3", "1.235 ft")] + [InlineData("s4", "1.2346 ft")] + [InlineData("s5", "1.23457 ft")] + [InlineData("s6", "1.234568 ft")] + public void SFormatEqualsSignificantDigits(string sFormatString, string expected) { - Assert.Equal(Length.Info.Name, length.ToString("q")); + Assert.Equal(expected, length.ToString(sFormatString, NumberFormatInfo.InvariantInfo)); } [Fact] @@ -70,11 +76,5 @@ public void UnsupportedFormatStringThrowsException() { Assert.Throws(() => length.ToString("z")); } - - [Fact] - public void VFormatEqualsValueToString() - { - Assert.Equal(length.Value.ToString(CultureInfo.CurrentUICulture), length.ToString("v")); - } } } diff --git a/UnitsNet.Tests/QuantityInfoTest.cs b/UnitsNet.Tests/QuantityInfoTest.cs index 58d26c7e59..51ab1ad90d 100644 --- a/UnitsNet.Tests/QuantityInfoTest.cs +++ b/UnitsNet.Tests/QuantityInfoTest.cs @@ -3,6 +3,7 @@ using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; using UnitsNet.Units; using Xunit; @@ -14,8 +15,7 @@ public class QuantityInfoTest public void Constructor_AssignsProperties() { var expectedZero = Length.FromCentimeters(10); - var expectedUnitInfos = new[] - { + var expectedUnitInfos = new UnitInfo[]{ new UnitInfo(LengthUnit.Centimeter, new BaseUnits(LengthUnit.Centimeter)), new UnitInfo(LengthUnit.Kilometer, new BaseUnits(LengthUnit.Kilometer)) }; @@ -34,56 +34,16 @@ public void Constructor_AssignsProperties() // Obsolete members #pragma warning disable 618 - Assert.Equal(expectedBaseUnit, info.BaseUnit); - Assert.Equal(new[] {"Centimeter", "Kilometer"}, info.UnitNames); + Assert.Equal( expectedBaseUnit, info.BaseUnit ); + Assert.Equal( new[] { "Centimeter", "Kilometer" }, info.UnitNames ); #pragma warning restore 618 } - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(QuantityType.Length, - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsBaseUnit_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(QuantityType.Length, - Length.Info.UnitInfos, null, Length.Zero, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(QuantityType.Length, - null, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsZero_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(QuantityType.Length, - Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions)); - } - - [Fact] - public void Constructor_GivenUndefinedAsQuantityType_ThrowsArgumentException() - { - Assert.Throws(() => new QuantityInfo(QuantityType.Undefined, - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); - } - [Fact] public void GenericsConstructor_AssignsProperties() { var expectedZero = Length.FromCentimeters(10); - var expectedUnitInfos = new[] - { + var expectedUnitInfos = new UnitInfo[]{ new UnitInfo(LengthUnit.Centimeter, new BaseUnits(LengthUnit.Centimeter)), new UnitInfo(LengthUnit.Kilometer, new BaseUnits(LengthUnit.Kilometer)) }; @@ -102,17 +62,31 @@ public void GenericsConstructor_AssignsProperties() // Obsolete members #pragma warning disable 618 - Assert.Equal(expectedBaseUnit, info.BaseUnit); - Assert.Equal(new[] {"Centimeter", "Kilometer"}, info.UnitNames); + Assert.Equal( expectedBaseUnit, info.BaseUnit ); + Assert.Equal( new[] { "Centimeter", "Kilometer" }, info.UnitNames ); #pragma warning restore 618 } + [Fact] + public void Constructor_GivenUndefinedAsQuantityType_ThrowsArgumentException() + { + Assert.Throws(() => new QuantityInfo(QuantityType.Undefined, + Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); + } + + [Fact] + public void GenericsConstructor_GivenUndefinedAsQuantityType_ThrowsArgumentException() + { + Assert.Throws(() => new QuantityInfo(QuantityType.Undefined, + Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); + } + [Fact] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() + public void Constructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() { - Assert.Throws(() => new QuantityInfo(QuantityType.Length, - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null)); + Assert.Throws(() => new QuantityInfo(QuantityType.Length, + null, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); } [Fact] @@ -125,36 +99,42 @@ public void GenericsConstructor_GivenNullAsUnitInfos_ThrowsArgumentNullException [Fact] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor_GivenNullAsZero_ThrowsArgumentNullException() + public void Constructor_GivenNullAsBaseUnit_ThrowsArgumentNullException() { - Assert.Throws(() => new QuantityInfo(QuantityType.Length, - Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions)); + Assert.Throws(() => new QuantityInfo(QuantityType.Length, + Length.Info.UnitInfos, null, Length.Zero, Length.BaseDimensions)); } [Fact] - public void GenericsConstructor_GivenUndefinedAsQuantityType_ThrowsArgumentException() + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + public void Constructor_GivenNullAsZero_ThrowsArgumentNullException() { - Assert.Throws(() => new QuantityInfo(QuantityType.Undefined, - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); + Assert.Throws(() => new QuantityInfo(QuantityType.Length, + Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions)); } [Fact] - public void GetUnitInfoFor_GivenBaseUnitsWithMultipleMatches_ThrowsInvalidOperationException() + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + public void GenericsConstructor_GivenNullAsZero_ThrowsArgumentNullException() { - var baseUnits = new BaseUnits(LengthUnit.Meter); - - var quantityInfo = new QuantityInfo(QuantityType.Length, - new[] {new UnitInfo(LengthUnit.Meter, baseUnits), new UnitInfo(LengthUnit.Foot, baseUnits)}, - LengthUnit.Meter, Length.Zero, Length.BaseDimensions); + Assert.Throws(() => new QuantityInfo(QuantityType.Length, + Length.Info.UnitInfos, Length.BaseUnit, null, Length.BaseDimensions)); + } - Assert.Throws(() => quantityInfo.GetUnitInfoFor(baseUnits)); + [Fact] + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + public void Constructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() + { + Assert.Throws(() => new QuantityInfo(QuantityType.Length, + Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null)); } [Fact] - public void GetUnitInfoFor_GivenBaseUnitsWithNoMatch_ThrowsInvalidOperationException() + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + public void GenericsConstructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() { - var baseUnitsWithNoMatch = new BaseUnits(mass: MassUnit.Kilogram); - Assert.Throws(() => Length.Info.GetUnitInfoFor(baseUnitsWithNoMatch)); + Assert.Throws(() => new QuantityInfo(QuantityType.Length, + Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null)); } [Fact] @@ -164,27 +144,30 @@ public void GetUnitInfoFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() } [Fact] - public void GetUnitInfosFor_GivenBaseUnitsWithMultipleMatches_ReturnsMultipleMatches() + public void GetUnitInfoFor_GivenBaseUnitsWithNoMatch_ThrowsInvalidOperationException() + { + var baseUnitsWithNoMatch = new BaseUnits(mass: MassUnit.Kilogram); + Assert.Throws(() => Length.Info.GetUnitInfoFor(baseUnitsWithNoMatch)); + } + + [Fact] + public void GetUnitInfoFor_GivenBaseUnitsWithMultipleMatches_ThrowsInvalidOperationException() { var baseUnits = new BaseUnits(LengthUnit.Meter); var quantityInfo = new QuantityInfo(QuantityType.Length, - new[] {new UnitInfo(LengthUnit.Meter, baseUnits), new UnitInfo(LengthUnit.Foot, baseUnits)}, + new UnitInfo[]{ + new UnitInfo(LengthUnit.Meter, baseUnits), + new UnitInfo(LengthUnit.Foot, baseUnits) }, LengthUnit.Meter, Length.Zero, Length.BaseDimensions); - var result = quantityInfo.GetUnitInfosFor(baseUnits); + Assert.Throws(() => quantityInfo.GetUnitInfoFor(baseUnits)); + } - Assert.Collection(result, - element1 => - { - Assert.Equal(LengthUnit.Meter, element1.Value); - Assert.Equal(baseUnits, element1.BaseUnits); - }, - element2 => - { - Assert.Equal(LengthUnit.Foot, element2.Value); - Assert.Equal(baseUnits, element2.BaseUnits); - }); + [Fact] + public void GetUnitInfosFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() + { + Assert.Throws(() => Length.Info.GetUnitInfosFor(null)); } [Fact] @@ -204,9 +187,29 @@ public void GetUnitInfosFor_GivenBaseUnitsWithOneMatch_ReturnsOneMatch() } [Fact] - public void GetUnitInfosFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() + public void GetUnitInfosFor_GivenBaseUnitsWithMultipleMatches_ReturnsMultipleMatches() { - Assert.Throws(() => Length.Info.GetUnitInfosFor(null)); + var baseUnits = new BaseUnits(LengthUnit.Meter); + + var quantityInfo = new QuantityInfo(QuantityType.Length, + new UnitInfo[]{ + new UnitInfo(LengthUnit.Meter, baseUnits), + new UnitInfo(LengthUnit.Foot, baseUnits) }, + LengthUnit.Meter, Length.Zero, Length.BaseDimensions); + + var result = quantityInfo.GetUnitInfosFor(baseUnits); + + Assert.Collection(result, + element1 => + { + Assert.Equal(LengthUnit.Meter, element1.Value); + Assert.Equal(baseUnits, element1.BaseUnits); + }, + element2 => + { + Assert.Equal(LengthUnit.Foot, element2.Value); + Assert.Equal(baseUnits, element2.BaseUnits); + } ); } } } diff --git a/UnitsNet.Tests/QuantityParserTests.cs b/UnitsNet.Tests/QuantityParserTests.cs index e3e5b12537..79f9a7bd72 100644 --- a/UnitsNet.Tests/QuantityParserTests.cs +++ b/UnitsNet.Tests/QuantityParserTests.cs @@ -15,7 +15,7 @@ public void Parse_MappedCustomUnit() unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "fooh"); var quantityParser = new QuantityParser(unitAbbreviationsCache); - var q = quantityParser.Parse("1 fooh", + HowMuch q = quantityParser.Parse("1 fooh", null, (value, unit) => new HowMuch((double) value, unit)); @@ -30,7 +30,7 @@ public void TryParse_MappedCustomUnit() unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "fooh"); var quantityParser = new QuantityParser(unitAbbreviationsCache); - var success = quantityParser.TryParse("1 fooh", + bool success = quantityParser.TryParse("1 fooh", null, (value, unit) => new HowMuch((double) value, unit), out HowMuch q); @@ -39,5 +39,6 @@ public void TryParse_MappedCustomUnit() Assert.Equal(HowMuchUnit.Some, q.Unit); Assert.Equal(1, q.Value); } + } } diff --git a/UnitsNet.Tests/QuantityTest.cs b/UnitsNet.Tests/QuantityTest.cs index 13ad4ac552..296a01eb68 100644 --- a/UnitsNet.Tests/QuantityTest.cs +++ b/UnitsNet.Tests/QuantityTest.cs @@ -4,6 +4,7 @@ using System; using System.Globalization; using System.Linq; +using JetBrains.Annotations; using UnitsNet.Units; using Xunit; @@ -29,7 +30,7 @@ public void From_GivenNaNOrInfinity_ThrowsArgumentException(double value) [InlineData(double.NegativeInfinity)] public void TryFrom_GivenNaNOrInfinity_ReturnsFalseAndNullQuantity(double value) { - Assert.False(Quantity.TryFrom(value, LengthUnit.Centimeter, out var parsedLength)); + Assert.False(Quantity.TryFrom(value, LengthUnit.Centimeter, out IQuantity parsedLength)); Assert.Null(parsedLength); } @@ -41,28 +42,6 @@ public void From_GivenValueAndUnit_ReturnsQuantity() Assert.Equal(Pressure.FromMegabars(3), Quantity.From(3, PressureUnit.Megabar)); } - [Fact] - public void FromQuantityType_GivenInvalidQuantityType_ThrowsArgumentException() - { - Assert.Throws(() => Quantity.FromQuantityType((QuantityType) (-1), 0.0)); - } - - [Fact] - public void FromQuantityType_GivenLengthQuantityType_ReturnsLengthQuantity() - { - var fromQuantity = Quantity.FromQuantityType(QuantityType.Length, 0.0); - - Assert.Equal(0.0, fromQuantity.Value); - Assert.Equal(QuantityType.Length, fromQuantity.Type); - Assert.Equal(Length.BaseUnit, fromQuantity.Unit); - } - - [Fact] - public void FromQuantityType_GivenUndefinedQuantityType_ThrowsArgumentException() - { - Assert.Throws(() => Quantity.FromQuantityType(QuantityType.Undefined, 0.0)); - } - [Fact] public void GetInfo_GivenLength_ReturnsQuantityInfoForLength() { @@ -70,7 +49,7 @@ public void GetInfo_GivenLength_ReturnsQuantityInfoForLength() var knownLengthUnitNames = new[] {"Meter", "Centimeter", "Kilometer"}; var lengthUnitCount = Enum.GetValues(typeof(LengthUnit)).Length - 1; // Exclude LengthUnit.Undefined - var quantityInfo = Quantity.GetInfo(QuantityType.Length); + QuantityInfo quantityInfo = Quantity.GetInfo(QuantityType.Length); Assert.Equal("Length", quantityInfo.Name); Assert.Equal(QuantityType.Length, quantityInfo.QuantityType); @@ -93,7 +72,7 @@ public void GetInfo_GivenMass_ReturnsQuantityInfoForMass() var knownMassUnitNames = new[] {"Kilogram", "Gram", "Tonne"}; var massUnitCount = Enum.GetValues(typeof(MassUnit)).Length - 1; // Exclude MassUnit.Undefined - var quantityInfo = Quantity.GetInfo(QuantityType.Mass); + QuantityInfo quantityInfo = Quantity.GetInfo(QuantityType.Mass); Assert.Equal("Mass", quantityInfo.Name); Assert.Equal(QuantityType.Mass, quantityInfo.QuantityType); @@ -112,7 +91,12 @@ public void GetInfo_GivenMass_ReturnsQuantityInfoForMass() [Fact] public void Infos_ReturnsKnownQuantityInfoObjects() { - var knownQuantityInfos = new[] {Quantity.GetInfo(QuantityType.Length), Quantity.GetInfo(QuantityType.Force), Quantity.GetInfo(QuantityType.Mass)}; + var knownQuantityInfos = new[] + { + Quantity.GetInfo(QuantityType.Length), + Quantity.GetInfo(QuantityType.Force), + Quantity.GetInfo(QuantityType.Mass) + }; var infos = Quantity.Infos; @@ -142,46 +126,46 @@ public void QuantityNames_ReturnsKnownNames() [Fact] public void TryFrom_GivenValueAndUnit_ReturnsQuantity() { - Assert.True(Quantity.TryFrom(3, LengthUnit.Centimeter, out var parsedLength)); + Assert.True(Quantity.TryFrom(3, LengthUnit.Centimeter, out IQuantity parsedLength)); Assert.Equal(Length.FromCentimeters(3), parsedLength); - Assert.True(Quantity.TryFrom(3, MassUnit.Tonne, out var parsedMass)); + Assert.True(Quantity.TryFrom(3, MassUnit.Tonne, out IQuantity parsedMass)); Assert.Equal(Mass.FromTonnes(3), parsedMass); - Assert.True(Quantity.TryFrom(3, PressureUnit.Megabar, out var parsedPressure)); + Assert.True(Quantity.TryFrom(3, PressureUnit.Megabar, out IQuantity parsedPressure)); Assert.Equal(Pressure.FromMegabars(3), parsedPressure); } [Fact] public void TryParse_GivenInvalidQuantityType_ReturnsFalseAndNullQuantity() { - Assert.False(Quantity.TryParse(typeof(DummyIQuantity), "3.0 cm", out var parsedLength)); + Assert.False(Quantity.TryParse(typeof(DummyIQuantity), "3.0 cm", out IQuantity parsedLength)); Assert.Null(parsedLength); } [Fact] public void TryParse_GivenInvalidString_ReturnsFalseAndNullQuantity() { - Assert.False(Quantity.TryParse(typeof(Length), "x cm", out var parsedLength)); + Assert.False(Quantity.TryParse(typeof(Length), "x cm", out IQuantity parsedLength)); Assert.Null(parsedLength); - Assert.False(Quantity.TryParse(typeof(Mass), "xt", out var parsedMass)); + Assert.False(Quantity.TryParse(typeof(Mass), "xt", out IQuantity parsedMass)); Assert.Null(parsedMass); - Assert.False(Quantity.TryParse(typeof(Pressure), "foo", out var parsedPressure)); + Assert.False(Quantity.TryParse(typeof(Pressure), "foo", out IQuantity parsedPressure)); Assert.Null(parsedPressure); } [Fact] public void TryParse_GivenValueAndUnit_ReturnsQuantity() { - Assert.True(Quantity.TryParse(typeof(Length), "3 cm", out var parsedLength)); + Assert.True(Quantity.TryParse(typeof(Length), "3 cm", out IQuantity parsedLength)); Assert.Equal(Length.FromCentimeters(3), parsedLength); - Assert.True(Quantity.TryParse(typeof(Mass), "03t", out var parsedMass)); + Assert.True(Quantity.TryParse(typeof(Mass), "03t", out IQuantity parsedMass)); Assert.Equal(Mass.FromTonnes(3), parsedMass); - Assert.True(Quantity.TryParse(NumberFormatInfo.InvariantInfo, typeof(Pressure), "3.0 Mbar", out var parsedPressure)); + Assert.True(Quantity.TryParse(NumberFormatInfo.InvariantInfo, typeof(Pressure), "3.0 Mbar", out IQuantity parsedPressure)); Assert.Equal(Pressure.FromMegabars(3), parsedPressure); } @@ -195,5 +179,27 @@ public void Types_ReturnsKnownQuantityTypes() Assert.Superset(knownQuantities.ToHashSet(), types.ToHashSet()); Assert.Equal(QuantityCount, types.Length); } + + [Fact] + public void FromQuantityType_GivenUndefinedQuantityType_ThrowsArgumentException() + { + Assert.Throws(() => Quantity.FromQuantityType(QuantityType.Undefined, 0.0)); + } + + [Fact] + public void FromQuantityType_GivenInvalidQuantityType_ThrowsArgumentException() + { + Assert.Throws(() => Quantity.FromQuantityType((QuantityType)(-1), 0.0)); + } + + [Fact] + public void FromQuantityType_GivenLengthQuantityType_ReturnsLengthQuantity() + { + var fromQuantity = Quantity.FromQuantityType(QuantityType.Length, 0.0); + + Assert.Equal(0.0, fromQuantity.Value); + Assert.Equal(QuantityType.Length, fromQuantity.Type); + Assert.Equal(Length.BaseUnit, fromQuantity.Unit); + } } } diff --git a/UnitsNet.Tests/QuantityTests.Ctor.cs b/UnitsNet.Tests/QuantityTests.Ctor.cs index 263ba43897..869a3df951 100644 --- a/UnitsNet.Tests/QuantityTests.Ctor.cs +++ b/UnitsNet.Tests/QuantityTests.Ctor.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; using System.Diagnostics.CodeAnalysis; using JetBrains.Annotations; using UnitsNet.Units; @@ -13,14 +10,99 @@ namespace UnitsNet.Tests public partial class QuantityTests { /// - /// Tests constructors of quantity types. + /// Tests constructors of quantity types. /// public class Ctor { - private static void AssertUnitValue(IQuantity actual, double expectedValue, Enum expectedUnit) + [Fact] + [SuppressMessage("ReSharper", "ObjectCreationAsStatement", Justification = "Only testing the ctor itself, not the resulting value.")] + public void DefaultCtorOfRepresentativeTypes_DoesNotThrow() { - Assert.Equal(expectedValue, actual.Value); - Assert.Equal(expectedUnit, actual.Unit); + // 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, MassUnit.Kilogram).Value); + Assert.Equal(5, new Mass(5d, MassUnit.Kilogram).Value); + Assert.Equal(MassUnit.Kilogram, new Mass(5L, MassUnit.Kilogram).Unit); + Assert.Equal(MassUnit.Kilogram, new Mass(5d, MassUnit.Kilogram).Unit); + + // decimal types + Assert.Equal(5, new Information(5L, InformationUnit.Bit).Value); + Assert.Equal(5, new Information(5m, InformationUnit.Bit).Value); + Assert.Equal(InformationUnit.Bit, new Information(5L, InformationUnit.Bit).Unit); + Assert.Equal(InformationUnit.Bit, new Information(5m, InformationUnit.Bit).Unit); + + // logarithmic types + Assert.Equal(5, new Level(5L, LevelUnit.Decibel).Value); + Assert.Equal(5, new Level(5d, LevelUnit.Decibel).Value); + Assert.Equal(LevelUnit.Decibel, new Level(5L, LevelUnit.Decibel).Unit); + Assert.Equal(LevelUnit.Decibel, new Level(5d, LevelUnit.Decibel).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); } [Fact] @@ -30,12 +112,12 @@ public void Constructor_UnitSystemGivenNull_ThrowsArgumentNullException() } /// - /// This test shows what quantities support the SI UnitSystem, which is not many. - /// UnitSystem is still experimental and this design will probably change at some point as we see problems with - /// ambiguity - /// as well as representing anything else but the SI unit system like CGS or British Engineering Units. - /// Extending the functionality of BaseUnits & UnitSystem · Issue #651 · angularsen/UnitsNet - /// https://github.com/angularsen/UnitsNet/issues/651 + /// This test shows what quantities support the SI UnitSystem, which is not many. + /// UnitSystem is still experimental and this design will probably change at some point as we see problems with ambiguity + /// as well as representing anything else but the SI unit system like CGS or British Engineering Units. + /// + /// Extending the functionality of BaseUnits & UnitSystem · Issue #651 · angularsen/UnitsNet + /// https://github.com/angularsen/UnitsNet/issues/651 /// [Fact] public void Ctor_WithValueAndSIUnitSystem_ReturnsQuantityWithSIUnitOrThrowsArgumentExceptionIfNotImplemented() @@ -137,97 +219,10 @@ public void Ctor_WithValueAndSIUnitSystem_ReturnsQuantityWithSIUnitOrThrowsArgum Assert.Throws(() => new Volume(1, UnitSystem.SI)); } - [Fact] - public void CtorWithOnlyValueOfRepresentativeTypes_SetsValueToGivenValueAndUnitToBaseUnit() - { -#pragma warning disable 618 - // double types - Assert.Equal(5, new Mass(5L, MassUnit.Kilogram).Value); - Assert.Equal(5, new Mass(5d, MassUnit.Kilogram).Value); - Assert.Equal(MassUnit.Kilogram, new Mass(5L, MassUnit.Kilogram).Unit); - Assert.Equal(MassUnit.Kilogram, new Mass(5d, MassUnit.Kilogram).Unit); - - // decimal types - Assert.Equal(5, new Information(5L, InformationUnit.Bit).Value); - Assert.Equal(5, new Information(5m, InformationUnit.Bit).Value); - Assert.Equal(InformationUnit.Bit, new Information(5L, InformationUnit.Bit).Unit); - Assert.Equal(InformationUnit.Bit, new Information(5m, InformationUnit.Bit).Unit); - - // logarithmic types - Assert.Equal(5, new Level(5L, LevelUnit.Decibel).Value); - Assert.Equal(5, new Level(5d, LevelUnit.Decibel).Value); - Assert.Equal(LevelUnit.Decibel, new Level(5L, LevelUnit.Decibel).Unit); - Assert.Equal(LevelUnit.Decibel, new Level(5d, LevelUnit.Decibel).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); - } - - [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(); - } - - /// - /// 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 DefaultCtorOfRepresentativeTypes_SetsValueToZeroAndUnitToBaseUnit() + private static void AssertUnitValue(IQuantity actual, double expectedValue, Enum expectedUnit) { - // 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); + Assert.Equal(expectedValue, actual.Value); + Assert.Equal(expectedUnit, actual.Unit); } } } diff --git a/UnitsNet.Tests/QuantityTests.ToString.cs b/UnitsNet.Tests/QuantityTests.ToString.cs index 5d68dbc5d2..e261daa6c6 100644 --- a/UnitsNet.Tests/QuantityTests.ToString.cs +++ b/UnitsNet.Tests/QuantityTests.ToString.cs @@ -14,21 +14,16 @@ public partial class QuantityTests public class ToStringTests { [Fact] - public void ConvertsToTheGivenUnit() + public void CreatedByDefaultCtor_ReturnsValueInBaseUnit() { - var oldCulture = CultureInfo.CurrentUICulture; - try - { - CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; - Assert.Equal("5,000 g", Mass.FromKilograms(5).ToUnit(MassUnit.Gram).ToString()); - Assert.Equal("5 kg", Mass.FromGrams(5000).ToUnit(MassUnit.Kilogram).ToString()); - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString()); - Assert.Equal("1.97 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString()); - } - finally - { - CultureInfo.CurrentUICulture = oldCulture; - } + // 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] @@ -65,28 +60,39 @@ public void CreatedByCtorWithValueAndUnit_ReturnsValueAndUnit() } [Fact] - public void CreatedByDefaultCtor_ReturnsValueInBaseUnit() + public void ReturnsTheOriginalValueAndUnit() { - // 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()); + var oldCulture = CultureInfo.CurrentUICulture; + try + { + CultureInfo.CurrentUICulture = 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 + { + CultureInfo.CurrentUICulture = oldCulture; + } } [Fact] - public void FormatsNumberUsingGivenCulture() + public void ConvertsToTheGivenUnit() { var oldCulture = CultureInfo.CurrentUICulture; try { CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString((IFormatProvider) null)); - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(CultureInfo.InvariantCulture)); - Assert.Equal("0,05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(new CultureInfo("nb-NO"))); + Assert.Equal("5,000 g", Mass.FromKilograms(5).ToUnit(MassUnit.Gram).ToString()); + Assert.Equal("5 kg", Mass.FromGrams(5000).ToUnit(MassUnit.Kilogram).ToString()); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString()); + Assert.Equal("1.97 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString()); } finally { @@ -95,15 +101,15 @@ public void FormatsNumberUsingGivenCulture() } [Fact] - public void FormatsNumberUsingGivenDigitsAfterRadix() + public void FormatsNumberUsingGivenCulture() { var oldCulture = CultureInfo.CurrentUICulture; try { CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; - Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString("s4")); - Assert.Equal("1.97 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString("s2")); - Assert.Equal("1.9685 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString("s4")); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString((IFormatProvider)null)); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(CultureInfo.InvariantCulture)); + Assert.Equal("0,05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString(new CultureInfo("nb-NO"))); } finally { @@ -112,21 +118,15 @@ public void FormatsNumberUsingGivenDigitsAfterRadix() } [Fact] - public void ReturnsTheOriginalValueAndUnit() + public void FormatsNumberUsingGivenDigitsAfterRadix() { var oldCulture = CultureInfo.CurrentUICulture; try { CultureInfo.CurrentUICulture = 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()); + Assert.Equal("0.05 m", Length.FromCentimeters(5).ToUnit(LengthUnit.Meter).ToString("s4")); + Assert.Equal("1.97 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString("s2")); + Assert.Equal("1.9685 in", Length.FromCentimeters(5).ToUnit(LengthUnit.Inch).ToString("s4")); } finally { diff --git a/UnitsNet.Tests/QuantityTests.cs b/UnitsNet.Tests/QuantityTests.cs index c0c5088d60..ab97ec0b6e 100644 --- a/UnitsNet.Tests/QuantityTests.cs +++ b/UnitsNet.Tests/QuantityTests.cs @@ -9,47 +9,47 @@ namespace UnitsNet.Tests { public partial class QuantityTests { - private static void AssertQuantityInfoRepresentsLength(QuantityInfo quantityInfo) + [Fact] + public void GetHashCodeForDifferentQuantitiesWithSameValuesAreNotEqual() { - Assert.Equal(Length.Zero, quantityInfo.Zero); - Assert.Equal("Length", quantityInfo.Name); - Assert.Equal(QuantityType.Length, quantityInfo.QuantityType); - - var lengthUnits = EnumUtils.GetEnumValues().Except(new[] {LengthUnit.Undefined}).ToArray(); - var lengthUnitNames = lengthUnits.Select(x => x.ToString()); + var length = new Length(1.0, (LengthUnit)2); + var area = new Area(1.0, (AreaUnit)2); - // Obsolete members -#pragma warning disable 618 - Assert.Equal(lengthUnits, quantityInfo.Units); - Assert.Equal(lengthUnitNames, quantityInfo.UnitNames); -#pragma warning restore 618 + Assert.NotEqual(length.GetHashCode(), area.GetHashCode()); } [Fact] - public void GetHashCodeForDifferentQuantitiesWithSameValuesAreNotEqual() + public void Length_QuantityInfo_ReturnsQuantityInfoAboutLength() { - var length = new Length(1.0, (LengthUnit) 2); - var area = new Area(1.0, (AreaUnit) 2); + var length = new Length(1, LengthUnit.Centimeter); - Assert.NotEqual(length.GetHashCode(), area.GetHashCode()); + QuantityInfo quantityInfo = length.QuantityInfo; + + AssertQuantityInfoRepresentsLength(quantityInfo); } [Fact] public void Length_Info_ReturnsQuantityInfoAboutLength() { - var quantityInfo = Length.Info; + QuantityInfo quantityInfo = Length.Info; AssertQuantityInfoRepresentsLength(quantityInfo); } - [Fact] - public void Length_QuantityInfo_ReturnsQuantityInfoAboutLength() + private static void AssertQuantityInfoRepresentsLength(QuantityInfo quantityInfo) { - var length = new Length(1, LengthUnit.Centimeter); + Assert.Equal(Length.Zero, quantityInfo.Zero); + Assert.Equal("Length", quantityInfo.Name); + Assert.Equal(QuantityType.Length, quantityInfo.QuantityType); - var quantityInfo = length.QuantityInfo; + var lengthUnits = EnumUtils.GetEnumValues().Except(new[] {LengthUnit.Undefined}).ToArray(); + var lengthUnitNames = lengthUnits.Select(x => x.ToString()); - AssertQuantityInfoRepresentsLength(quantityInfo); + // Obsolete members +#pragma warning disable 618 + Assert.Equal(lengthUnits, quantityInfo.Units); + Assert.Equal(lengthUnitNames, quantityInfo.UnitNames); +#pragma warning restore 618 } } } diff --git a/UnitsNet.Tests/QuantityTypeConverterTest.cs b/UnitsNet.Tests/QuantityTypeConverterTest.cs index e51bea71ca..5de7b6d269 100644 --- a/UnitsNet.Tests/QuantityTypeConverterTest.cs +++ b/UnitsNet.Tests/QuantityTypeConverterTest.cs @@ -6,38 +6,36 @@ using System.Globalization; using System.Reflection; using UnitsNet.Tests.Helpers; -using UnitsNet.Units; using Xunit; namespace UnitsNet.Tests { public class QuantityTypeConverterTest { - static QuantityTypeConverterTest() - { - // NOTE: After this, you can use your TypeConverter. - AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; - } - // https://stackoverflow.com/questions/3612909/why-is-this-typeconverter-not-working private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { - var domain = (AppDomain) sender; - foreach (var asm in domain.GetAssemblies()) + AppDomain domain = (AppDomain)sender; + foreach (Assembly asm in domain.GetAssemblies()) { if (asm.FullName == args.Name) { return asm; } } - return null; } + static QuantityTypeConverterTest() + { + // NOTE: After this, you can use your TypeConverter. + AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); + } + /// - /// Is used for tests that are culture dependent + /// Is used for tests that are culture dependent /// - private static readonly CultureInfo culture = CultureInfo.GetCultureInfo("en-US"); + private static CultureInfo culture = CultureInfo.GetCultureInfo("en-US"); [Theory] [InlineData(typeof(string), true)] @@ -49,7 +47,7 @@ public void CanConvertFrom_GivenSomeTypes(Type value, bool expectedResult) { var converter = new QuantityTypeConverter(); - var canConvertFrom = converter.CanConvertFrom(value); + bool canConvertFrom = converter.CanConvertFrom(value); Assert.Equal(expectedResult, canConvertFrom); } @@ -64,237 +62,254 @@ public void CanConvertTo_GivenSomeTypes(Type value, bool expectedResult) { var converter = new QuantityTypeConverter(); - var canConvertTo = converter.CanConvertTo(value); + bool canConvertTo = converter.CanConvertTo(value); Assert.Equal(expectedResult, canConvertTo); } [Theory] - [InlineData("1mm", 1, LengthUnit.Millimeter)] - [InlineData("1m", 1, LengthUnit.Meter)] - [InlineData("1", 1, LengthUnit.Meter)] - [InlineData("1km", 1, LengthUnit.Kilometer)] - public void ConvertFrom_GivenQuantityStringAndContextWithNoAttributes_ReturnsQuantityWithBaseUnitIfNotSpecified(string str, double expectedValue, - Enum expectedUnit) + [InlineData("1mm", 1, Units.LengthUnit.Millimeter)] + [InlineData("1m", 1, Units.LengthUnit.Meter)] + [InlineData("1", 1, Units.LengthUnit.Meter)] + [InlineData("1km", 1, Units.LengthUnit.Kilometer)] + public void ConvertFrom_GivenQuantityStringAndContextWithNoAttributes_ReturnsQuantityWithBaseUnitIfNotSpecified(string str, double expectedValue, Enum expectedUnit) { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - var convertedValue = (Length) converter.ConvertFrom(context, culture, str); + var convertedValue = (Length)converter.ConvertFrom(context, culture, str); Assert.Equal(expectedValue, convertedValue.Value); Assert.Equal(expectedUnit, convertedValue.Unit); } [Theory] - [InlineData("1mm", 1, LengthUnit.Millimeter)] - [InlineData("1m", 1, LengthUnit.Meter)] - [InlineData("1", 1, LengthUnit.Centimeter)] - [InlineData("1km", 1, LengthUnit.Kilometer)] - public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAttribute_ReturnsQuantityWithGivenDefaultUnitIfNotSpecified(string str, - double expectedValue, Enum expectedUnit) + [InlineData("1mm", 1, Units.LengthUnit.Millimeter)] + [InlineData("1m", 1, Units.LengthUnit.Meter)] + [InlineData("1", 1, Units.LengthUnit.Centimeter)] + [InlineData("1km", 1, Units.LengthUnit.Kilometer)] + public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAttribute_ReturnsQuantityWithGivenDefaultUnitIfNotSpecified(string str, double expectedValue, Enum expectedUnit) { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DefaultUnitAttribute(LengthUnit.Centimeter)}); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] + { + new DefaultUnitAttribute(Units.LengthUnit.Centimeter) + }); - var convertedValue = (Length) converter.ConvertFrom(context, culture, str); + var convertedValue = (Length)converter.ConvertFrom(context, culture, str); Assert.Equal(expectedValue, convertedValue.Value); Assert.Equal(expectedUnit, convertedValue.Unit); } [Theory] - [InlineData("1mm", 0.001, LengthUnit.Meter)] - [InlineData("1m", 1, LengthUnit.Meter)] - [InlineData("1", 0.01, LengthUnit.Meter)] - [InlineData("1km", 1000, LengthUnit.Meter)] - public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAndConvertToUnitAttributes_ReturnsQuantityConvertedToUnit(string str, - double expectedValue, Enum expectedUnit) + [InlineData("1mm", 0.001, Units.LengthUnit.Meter)] + [InlineData("1m", 1, Units.LengthUnit.Meter)] + [InlineData("1", 0.01, Units.LengthUnit.Meter)] + [InlineData("1km", 1000, Units.LengthUnit.Meter)] + public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAndConvertToUnitAttributes_ReturnsQuantityConvertedToUnit(string str, double expectedValue, Enum expectedUnit) { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", - new Attribute[] {new DefaultUnitAttribute(LengthUnit.Centimeter), new ConvertToUnitAttribute(LengthUnit.Meter)}); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] + { + new DefaultUnitAttribute(Units.LengthUnit.Centimeter), + new ConvertToUnitAttribute(Units.LengthUnit.Meter) + }); - var convertedValue = (Length) converter.ConvertFrom(context, culture, str); + var convertedValue = (Length)converter.ConvertFrom(context, culture, str); Assert.Equal(expectedValue, convertedValue.Value); Assert.Equal(expectedUnit, convertedValue.Unit); } - [Theory] - [InlineData(typeof(Length))] - [InlineData(typeof(IQuantity))] - [InlineData(typeof(object))] - public void ConvertTo_GivenWrongType_ThrowsNotSupportedException(Type value) + [Fact] + public void ConvertFrom_GivenEmptyString_ThrowsNotSupportedException() { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - var length = Length.FromMeters(1); - Assert.Throws(() => converter.ConvertTo(length, value)); + Assert.Throws(() => converter.ConvertFrom(context, culture, "")); } [Fact] - public void ConvertFrom_GivenDefaultUnitAttributeWithWrongUnitType_ThrowsArgumentException() + public void ConvertFrom_GivenWrongQuantity_ThrowsArgumentException() { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DefaultUnitAttribute(VolumeUnit.CubicMeter)}); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Throws(() => converter.ConvertFrom(context, culture, "1")); + Assert.Throws(() => converter.ConvertFrom(context, culture, "1m^2")); } - [Fact] - public void ConvertFrom_GivenEmptyString_ThrowsNotSupportedException() + [Theory] + [InlineData(typeof(Length))] + [InlineData(typeof(IQuantity))] + [InlineData(typeof(object))] + public void ConvertTo_GivenWrongType_ThrowsNotSupportedException(Type value) { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + Length length = Length.FromMeters(1); - Assert.Throws(() => converter.ConvertFrom(context, culture, "")); + Assert.Throws(() => converter.ConvertTo(length, value)); } [Fact] - public void ConvertFrom_GivenStringWithPower_1() + public void ConvertTo_GivenStringType_ReturnsQuantityString() { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + Length length = Length.FromMeters(1); - Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, culture, "1m")); - Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, culture, "1m^1")); + string convertedQuantity = (string)converter.ConvertTo(length, typeof(string)); + + Assert.Equal("1 m", convertedQuantity); } [Fact] - public void ConvertFrom_GivenStringWithPower_2() + public void ConvertTo_GivenSomeQuantitysAndContextWithNoAttributes_ReturnsQuantityStringInUnitOfQuantity() { - var converter = new QuantityTypeConverter(); + var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + Length length = Length.FromMeters(1); - Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, culture, "1m²")); - Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, culture, "1m^2")); + string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + + Assert.Equal("1 m", convertedQuantity); } [Fact] - public void ConvertFrom_GivenStringWithPower_3() + public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUnitDefaultFormating() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] + { + new DisplayAsUnitAttribute(Units.LengthUnit.Decimeter) + }); + Length length = Length.FromMeters(1); - Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, culture, "1m³")); - Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, culture, "1m^3")); + string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + + Assert.Equal("10 dm", convertedQuantity); } [Fact] - public void ConvertFrom_GivenStringWithPower_4() + public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUnitFormateAsValueOnly() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] + { + new DisplayAsUnitAttribute(Units.LengthUnit.Decimeter, "v") + }); + Length length = Length.FromMeters(1); - Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, culture, "1m⁴")); - Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, culture, "1m^4")); + string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + + Assert.Equal("10", convertedQuantity); } [Fact] - public void ConvertFrom_GivenStringWithPower_minus1() + public void ConvertTo_TestDisplayAsFormattingWithoutDefinedUnit_ReturnsQuantityStringWithQuantetiesUnitAndFormatedAsValueOnly() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] + { + new DisplayAsUnitAttribute(null, "v") + }); + Length length = Length.FromMeters(1); - Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, culture, "1K⁻¹")); - Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, culture, "1K^-1")); + string convertedQuantity = (string)converter.ConvertTo(context, culture, length, typeof(string)); + + Assert.Equal("1", convertedQuantity); } [Fact] - public void ConvertFrom_GivenStringWithPower_minus2() + public void ConvertTo_GivenSomeQuantitysAndContextWithDisplayAsUnitAttributes_ReturnsQuantityStringInSpecifiedDisplayUnit() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] + { + new DisplayAsUnitAttribute(Units.LengthUnit.Decimeter) + }); + Length length = Length.FromMeters(1); - Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg·s⁻¹·m⁻²")); - Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg·s^-1·m^-2")); - Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg*s^-1*m^-2")); + string convertedQuantityDefaultCulture = (string)converter.ConvertTo(length, typeof(string)); + string convertedQuantitySpecificCulture = (string)converter.ConvertTo(context, culture, length, typeof(string)); + + Assert.Equal("1 m", convertedQuantityDefaultCulture); + Assert.Equal("10 dm", convertedQuantitySpecificCulture); } [Fact] - public void ConvertFrom_GivenWrongQuantity_ThrowsArgumentException() + public void ConvertFrom_GivenDefaultUnitAttributeWithWrongUnitType_ThrowsArgumentException() { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] + { + new DefaultUnitAttribute(Units.VolumeUnit.CubicMeter) + }); - Assert.Throws(() => converter.ConvertFrom(context, culture, "1m^2")); + Assert.Throws(() => converter.ConvertFrom(context, culture, "1")); } [Fact] - public void ConvertTo_GivenSomeQuantitysAndContextWithDisplayAsUnitAttributes_ReturnsQuantityStringInSpecifiedDisplayUnit() + public void ConvertFrom_GivenStringWithPower_1() { var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DisplayAsUnitAttribute(LengthUnit.Decimeter)}); - var length = Length.FromMeters(1); - - var convertedQuantityDefaultCulture = (string) converter.ConvertTo(length, typeof(string)); - var convertedQuantitySpecificCulture = (string) converter.ConvertTo(context, culture, length, typeof(string)); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal("1 m", convertedQuantityDefaultCulture); - Assert.Equal("10 dm", convertedQuantitySpecificCulture); + Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, culture, "1m")); + Assert.Equal(Length.FromMeters(1), converter.ConvertFrom(context, culture, "1m^1")); } [Fact] - public void ConvertTo_GivenSomeQuantitysAndContextWithNoAttributes_ReturnsQuantityStringInUnitOfQuantity() + public void ConvertFrom_GivenStringWithPower_2() { - var converter = new QuantityTypeConverter(); + var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - var length = Length.FromMeters(1); - - var convertedQuantity = (string) converter.ConvertTo(context, culture, length, typeof(string)); - Assert.Equal("1 m", convertedQuantity); + Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, culture, "1m²")); + Assert.Equal(Area.FromSquareMeters(1), converter.ConvertFrom(context, culture, "1m^2")); } [Fact] - public void ConvertTo_GivenStringType_ReturnsQuantityString() + public void ConvertFrom_GivenStringWithPower_3() { - var converter = new QuantityTypeConverter(); + var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - var length = Length.FromMeters(1); - var convertedQuantity = (string) converter.ConvertTo(length, typeof(string)); - - Assert.Equal("1 m", convertedQuantity); + Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, culture, "1m³")); + Assert.Equal(Volume.FromCubicMeters(1), converter.ConvertFrom(context, culture, "1m^3")); } [Fact] - public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUnitDefaultFormating() + public void ConvertFrom_GivenStringWithPower_4() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DisplayAsUnitAttribute(LengthUnit.Decimeter)}); - var length = Length.FromMeters(1); - - var convertedQuantity = (string) converter.ConvertTo(context, culture, length, typeof(string)); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal("10 dm", convertedQuantity); + Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, culture, "1m⁴")); + Assert.Equal(AreaMomentOfInertia.FromMetersToTheFourth(1), converter.ConvertFrom(context, culture, "1m^4")); } [Fact] - public void ConvertTo_TestDisplayAsFormatting_ReturnsQuantityStringWithDisplayUnitFormateAsValueOnly() + public void ConvertFrom_GivenStringWithPower_minus1() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = - new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DisplayAsUnitAttribute(LengthUnit.Decimeter, "v")}); - var length = Length.FromMeters(1); - - var convertedQuantity = (string) converter.ConvertTo(context, culture, length, typeof(string)); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal("10", convertedQuantity); + Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, culture, "1K⁻¹")); + Assert.Equal(CoefficientOfThermalExpansion.FromInverseKelvin(1), converter.ConvertFrom(context, culture, "1K^-1")); } [Fact] - public void ConvertTo_TestDisplayAsFormattingWithoutDefinedUnit_ReturnsQuantityStringWithQuantetiesUnitAndFormatedAsValueOnly() + public void ConvertFrom_GivenStringWithPower_minus2() { - var converter = new QuantityTypeConverter(); - ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] {new DisplayAsUnitAttribute(null, "v")}); - var length = Length.FromMeters(1); - - var convertedQuantity = (string) converter.ConvertTo(context, culture, length, typeof(string)); + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Equal("1", convertedQuantity); + Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg·s⁻¹·m⁻²")); + Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg·s^-1·m^-2")); + Assert.Equal(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), converter.ConvertFrom(context, culture, "1kg*s^-1*m^-2")); } } } diff --git a/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs b/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs index c795ca7126..ce7a36b980 100644 --- a/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs +++ b/UnitsNet.Tests/UnitAbbreviationsCacheFixture.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using Xunit; +using Xunit; namespace UnitsNet.Tests { diff --git a/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs index e08988a2f1..5103231a36 100644 --- a/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs +++ b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs @@ -2,7 +2,9 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; +using System.Linq; using UnitsNet.Units; using Xunit; using Xunit.Abstractions; @@ -12,11 +14,6 @@ namespace UnitsNet.Tests [Collection(nameof(UnitAbbreviationsCacheFixture))] public class UnitAbbreviationsCacheTests { - public UnitAbbreviationsCacheTests(ITestOutputHelper output) - { - _output = output; - } - private readonly ITestOutputHelper _output; private const string AmericanCultureName = "en-US"; private const string RussianCultureName = "ru-RU"; @@ -26,6 +23,11 @@ public UnitAbbreviationsCacheTests(ITestOutputHelper output) private static readonly IFormatProvider NorwegianCulture = new CultureInfo(NorwegianCultureName); private static readonly IFormatProvider RussianCulture = new CultureInfo(RussianCultureName); + public UnitAbbreviationsCacheTests(ITestOutputHelper output) + { + _output = output; + } + // The default, parameterless ToString() method uses 2 sigifnificant digits after the radix point. [Theory] [InlineData(0, "0 m")] @@ -35,7 +37,7 @@ public UnitAbbreviationsCacheTests(ITestOutputHelper output) [InlineData(0.115, "0.12 m")] public void DefaultToStringFormatting(double value, string expected) { - var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); Assert.Equal(expected, actual); } @@ -44,7 +46,6 @@ private enum CustomUnit // ReSharper disable UnusedMember.Local Undefined = 0, Unit1, - Unit2 // ReSharper restore UnusedMember.Local } @@ -82,7 +83,7 @@ public void DecimalRadixPointCultureFormatting(string culture) [InlineData("es-MX")] public void CommaDigitGroupingCultureFormatting(string cultureName) { - var culture = GetCulture(cultureName); + CultureInfo culture = GetCulture(cultureName); Assert.Equal("1,111 m", Length.FromMeters(1111).ToUnit(LengthUnit.Meter).ToString(culture)); // Feet/Inch and Stone/Pound combinations are only used (customarily) in the US, UK and maybe Ireland - all English speaking countries. @@ -126,7 +127,7 @@ public void DecimalPointDigitGroupingCultureFormatting(string culture) public void RoundingErrorsWithSignificantDigitsAfterRadixFormatting(double value, string significantDigitsAfterRadixFormatString, string expected) { - var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(significantDigitsAfterRadixFormatString, AmericanCulture); + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(significantDigitsAfterRadixFormatString, AmericanCulture); Assert.Equal(expected, actual); } @@ -138,7 +139,7 @@ public void RoundingErrorsWithSignificantDigitsAfterRadixFormatting(double value [InlineData(1.99e-4, "1.99e-04 m")] public void ScientificNotationLowerInterval(double value, string expected) { - var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); Assert.Equal(expected, actual); } @@ -149,7 +150,7 @@ public void ScientificNotationLowerInterval(double value, string expected) [InlineData(999.99, "999.99 m")] public void FixedPointNotationIntervalFormatting(double value, string expected) { - var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); Assert.Equal(expected, actual); } @@ -161,7 +162,7 @@ public void FixedPointNotationIntervalFormatting(double value, string expected) [InlineData(999999.99, "999,999.99 m")] public void FixedPointNotationWithDigitGroupingIntervalFormatting(double value, string expected) { - var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); Assert.Equal(expected, actual); } @@ -172,18 +173,10 @@ public void FixedPointNotationWithDigitGroupingIntervalFormatting(double value, [InlineData(double.MaxValue, "1.8e+308 m")] public void ScientificNotationUpperIntervalFormatting(double value, string expected) { - var actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); + string actual = Length.FromMeters(value).ToUnit(LengthUnit.Meter).ToString(AmericanCulture); Assert.Equal(expected, actual); } - /// - /// Convenience method to the proper culture parameter type. - /// - private static CultureInfo GetCulture(string cultureName) - { - return new CultureInfo(cultureName); - } - [Fact] public void AllUnitsImplementToStringForInvariantCulture() { @@ -204,6 +197,47 @@ public void AllUnitsImplementToStringForInvariantCulture() Assert.Equal("3 st 7 lb", Mass.FromStonePounds(3, 7).StonePounds.ToString()); } + [Fact] + public void ToString_WithNorwegianCulture() + { + Assert.Equal("1 °", Angle.FromDegrees(1).ToUnit(AngleUnit.Degree).ToString(NorwegianCulture)); + Assert.Equal("1 m²", Area.FromSquareMeters(1).ToUnit(AreaUnit.SquareMeter).ToString(NorwegianCulture)); + Assert.Equal("1 V", ElectricPotential.FromVolts(1).ToUnit(ElectricPotentialUnit.Volt).ToString(NorwegianCulture)); + Assert.Equal("1 m³/s", VolumeFlow.FromCubicMetersPerSecond(1).ToUnit(VolumeFlowUnit.CubicMeterPerSecond).ToString(NorwegianCulture)); + Assert.Equal("1 N", Force.FromNewtons(1).ToUnit(ForceUnit.Newton).ToString(NorwegianCulture)); + Assert.Equal("1 m", Length.FromMeters(1).ToUnit(LengthUnit.Meter).ToString(NorwegianCulture)); + Assert.Equal("1 kg", Mass.FromKilograms(1).ToUnit(MassUnit.Kilogram).ToString(NorwegianCulture)); + Assert.Equal("1 Pa", Pressure.FromPascals(1).ToUnit(PressureUnit.Pascal).ToString(NorwegianCulture)); + Assert.Equal("1 rad/s", RotationalSpeed.FromRadiansPerSecond(1).ToUnit(RotationalSpeedUnit.RadianPerSecond).ToString(NorwegianCulture)); + Assert.Equal("1 K", Temperature.FromKelvins(1).ToUnit(TemperatureUnit.Kelvin).ToString(NorwegianCulture)); + Assert.Equal("1 N·m", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(NorwegianCulture)); + Assert.Equal("1 m³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(NorwegianCulture)); + } + + [Fact] + public void ToString_WithRussianCulture() + { + Assert.Equal("1 °", Angle.FromDegrees(1).ToUnit(AngleUnit.Degree).ToString(RussianCulture)); + Assert.Equal("1 м²", Area.FromSquareMeters(1).ToUnit(AreaUnit.SquareMeter).ToString(RussianCulture)); + Assert.Equal("1 В", ElectricPotential.FromVolts(1).ToUnit(ElectricPotentialUnit.Volt).ToString(RussianCulture)); + Assert.Equal("1 м³/с", VolumeFlow.FromCubicMetersPerSecond(1).ToUnit(VolumeFlowUnit.CubicMeterPerSecond).ToString(RussianCulture)); + Assert.Equal("1 Н", Force.FromNewtons(1).ToUnit(ForceUnit.Newton).ToString(RussianCulture)); + Assert.Equal("1 м", Length.FromMeters(1).ToUnit(LengthUnit.Meter).ToString(RussianCulture)); + Assert.Equal("1 кг", Mass.FromKilograms(1).ToUnit(MassUnit.Kilogram).ToString(RussianCulture)); + Assert.Equal("1 Па", Pressure.FromPascals(1).ToUnit(PressureUnit.Pascal).ToString(RussianCulture)); + Assert.Equal("1 рад/с", RotationalSpeed.FromRadiansPerSecond(1).ToUnit(RotationalSpeedUnit.RadianPerSecond).ToString(RussianCulture)); + Assert.Equal("1 K", Temperature.FromKelvins(1).ToUnit(TemperatureUnit.Kelvin).ToString(RussianCulture)); + Assert.Equal("1 Н·м", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(RussianCulture)); + Assert.Equal("1 м³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(RussianCulture)); + } + + [Fact] + public void GetDefaultAbbreviationThrowsNotImplementedExceptionIfNoneExist() + { + var unitAbbreviationCache = new UnitAbbreviationsCache(); + Assert.Throws(() => unitAbbreviationCache.GetDefaultAbbreviation(CustomUnit.Unit1)); + } + [Fact] public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() { @@ -222,7 +256,7 @@ public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() abbreviationsCache.MapUnitToAbbreviation(CustomUnit.Unit1, AmericanCulture, "US english abbreviation for Unit1"); // Act - var abbreviation = abbreviationsCache.GetDefaultAbbreviation(CustomUnit.Unit1, zuluCulture); + string abbreviation = abbreviationsCache.GetDefaultAbbreviation(CustomUnit.Unit1, zuluCulture); // Assert Assert.Equal("US english abbreviation for Unit1", abbreviation); @@ -234,13 +268,6 @@ public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() } } - [Fact] - public void GetDefaultAbbreviationThrowsNotImplementedExceptionIfNoneExist() - { - var unitAbbreviationCache = new UnitAbbreviationsCache(); - Assert.Throws(() => unitAbbreviationCache.GetDefaultAbbreviation(CustomUnit.Unit1)); - } - [Fact] public void MapUnitToAbbreviation_AddCustomUnit_DoesNotOverrideDefaultAbbreviationForAlreadyMappedUnits() { @@ -250,16 +277,6 @@ public void MapUnitToAbbreviation_AddCustomUnit_DoesNotOverrideDefaultAbbreviati Assert.Equal("m²", cache.GetDefaultAbbreviation(AreaUnit.SquareMeter)); } - [Fact] - public void MapUnitToDefaultAbbreviation_GivenCustomAbbreviation_SetsAbbreviationUsedByQuantityToString() - { - // Use a distinct culture here so that we don't mess up other tests that may rely on the default cache. - var newZealandCulture = GetCulture("en-NZ"); - UnitAbbreviationsCache.Default.MapUnitToDefaultAbbreviation(AreaUnit.SquareMeter, newZealandCulture, "m^2"); - - Assert.Equal("1 m^2", Area.FromSquareMeters(1).ToString(newZealandCulture)); - } - [Fact] public void MapUnitToDefaultAbbreviation_GivenUnitAndCulture_SetsDefaultAbbreviationForUnitAndCulture() { @@ -270,37 +287,21 @@ public void MapUnitToDefaultAbbreviation_GivenUnitAndCulture_SetsDefaultAbbrevia } [Fact] - public void ToString_WithNorwegianCulture() + public void MapUnitToDefaultAbbreviation_GivenCustomAbbreviation_SetsAbbreviationUsedByQuantityToString() { - Assert.Equal("1 °", Angle.FromDegrees(1).ToUnit(AngleUnit.Degree).ToString(NorwegianCulture)); - Assert.Equal("1 m²", Area.FromSquareMeters(1).ToUnit(AreaUnit.SquareMeter).ToString(NorwegianCulture)); - Assert.Equal("1 V", ElectricPotential.FromVolts(1).ToUnit(ElectricPotentialUnit.Volt).ToString(NorwegianCulture)); - Assert.Equal("1 m³/s", VolumeFlow.FromCubicMetersPerSecond(1).ToUnit(VolumeFlowUnit.CubicMeterPerSecond).ToString(NorwegianCulture)); - Assert.Equal("1 N", Force.FromNewtons(1).ToUnit(ForceUnit.Newton).ToString(NorwegianCulture)); - Assert.Equal("1 m", Length.FromMeters(1).ToUnit(LengthUnit.Meter).ToString(NorwegianCulture)); - Assert.Equal("1 kg", Mass.FromKilograms(1).ToUnit(MassUnit.Kilogram).ToString(NorwegianCulture)); - Assert.Equal("1 Pa", Pressure.FromPascals(1).ToUnit(PressureUnit.Pascal).ToString(NorwegianCulture)); - Assert.Equal("1 rad/s", RotationalSpeed.FromRadiansPerSecond(1).ToUnit(RotationalSpeedUnit.RadianPerSecond).ToString(NorwegianCulture)); - Assert.Equal("1 K", Temperature.FromKelvins(1).ToUnit(TemperatureUnit.Kelvin).ToString(NorwegianCulture)); - Assert.Equal("1 N·m", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(NorwegianCulture)); - Assert.Equal("1 m³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(NorwegianCulture)); + // Use a distinct culture here so that we don't mess up other tests that may rely on the default cache. + var newZealandCulture = GetCulture("en-NZ"); + UnitAbbreviationsCache.Default.MapUnitToDefaultAbbreviation(AreaUnit.SquareMeter, newZealandCulture, "m^2"); + + Assert.Equal("1 m^2", Area.FromSquareMeters(1).ToString(newZealandCulture)); } - [Fact] - public void ToString_WithRussianCulture() + /// + /// Convenience method to the proper culture parameter type. + /// + private static CultureInfo GetCulture(string cultureName) { - Assert.Equal("1 °", Angle.FromDegrees(1).ToUnit(AngleUnit.Degree).ToString(RussianCulture)); - Assert.Equal("1 м²", Area.FromSquareMeters(1).ToUnit(AreaUnit.SquareMeter).ToString(RussianCulture)); - Assert.Equal("1 В", ElectricPotential.FromVolts(1).ToUnit(ElectricPotentialUnit.Volt).ToString(RussianCulture)); - Assert.Equal("1 м³/с", VolumeFlow.FromCubicMetersPerSecond(1).ToUnit(VolumeFlowUnit.CubicMeterPerSecond).ToString(RussianCulture)); - Assert.Equal("1 Н", Force.FromNewtons(1).ToUnit(ForceUnit.Newton).ToString(RussianCulture)); - Assert.Equal("1 м", Length.FromMeters(1).ToUnit(LengthUnit.Meter).ToString(RussianCulture)); - Assert.Equal("1 кг", Mass.FromKilograms(1).ToUnit(MassUnit.Kilogram).ToString(RussianCulture)); - Assert.Equal("1 Па", Pressure.FromPascals(1).ToUnit(PressureUnit.Pascal).ToString(RussianCulture)); - Assert.Equal("1 рад/с", RotationalSpeed.FromRadiansPerSecond(1).ToUnit(RotationalSpeedUnit.RadianPerSecond).ToString(RussianCulture)); - Assert.Equal("1 K", Temperature.FromKelvins(1).ToUnit(TemperatureUnit.Kelvin).ToString(RussianCulture)); - Assert.Equal("1 Н·м", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(RussianCulture)); - Assert.Equal("1 м³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(RussianCulture)); + return new CultureInfo(cultureName); } } } diff --git a/UnitsNet.Tests/UnitConverterTest.cs b/UnitsNet.Tests/UnitConverterTest.cs index 2d198b428c..c94ef6159e 100644 --- a/UnitsNet.Tests/UnitConverterTest.cs +++ b/UnitsNet.Tests/UnitConverterTest.cs @@ -10,6 +10,88 @@ namespace UnitsNet.Tests { public class UnitConverterTest { + [Fact] + public void CustomConversionWithSameQuantityType() + { + Length ConversionFunction(Length from) => Length.FromInches(18); + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, ConversionFunction); + + var foundConversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Inch); + var converted = foundConversionFunction(Length.FromMeters(1.0)); + + Assert.Equal(Length.FromInches(18), converted); + } + + [Fact] + public void CustomConversionWithSameQuantityTypeByTypeParam() + { + Length ConversionFunction(Length from) => Length.FromInches(18); + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, (ConversionFunction) ConversionFunction); + + var foundConversionFunction = unitConverter.GetConversionFunction(typeof(Length), LengthUnit.Meter, typeof(Length), LengthUnit.Inch); + var converted = foundConversionFunction(Length.FromMeters(1.0)); + + Assert.Equal(Length.FromInches(18), converted); + } + + [Fact] + public void CustomConversionWithDifferentQuantityTypes() + { + IQuantity ConversionFunction(IQuantity from) => Length.FromInches(18); + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(MassUnit.Grain, LengthUnit.Inch, ConversionFunction); + + var foundConversionFunction = unitConverter.GetConversionFunction(MassUnit.Grain, LengthUnit.Inch); + var converted = foundConversionFunction(Mass.FromGrains(100)); + + Assert.Equal(Length.FromInches(18), converted); + } + + [Fact] + public void CustomConversionWithDifferentQuantityTypesByTypeParam() + { + IQuantity ConversionFunction(IQuantity from) => Length.FromInches(18); + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(MassUnit.Grain, LengthUnit.Inch, ConversionFunction); + + var foundConversionFunction = unitConverter.GetConversionFunction(typeof(Mass), MassUnit.Grain, typeof(Length), LengthUnit.Inch); + var converted = foundConversionFunction(Mass.FromGrains(100)); + + Assert.Equal(Length.FromInches(18), converted); + } + + [Fact] + public void TryCustomConversionForOilBarrelsToUsGallons() + { + Volume ConversionFunction(Volume from) => Volume.FromUsGallons(from.Value * 42); + + var unitConverter = new UnitConverter(); + unitConverter.SetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.UsGallon, ConversionFunction); + + var foundConversionFunction = unitConverter.GetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.UsGallon); + var converted = foundConversionFunction(Volume.FromOilBarrels(1)); + + Assert.Equal(Volume.FromUsGallons(42), converted); + } + + [Fact] + public void ConversionToSameUnit_ReturnsSameQuantity() + { + var unitConverter = new UnitConverter(); + + var foundConversionFunction = unitConverter.GetConversionFunction(HowMuchUnit.ATon, HowMuchUnit.ATon); + var converted = foundConversionFunction(new HowMuch(39, HowMuchUnit.Some)); // Intentionally pass the wrong unit here, to test that the exact same quantity is returned + + Assert.Equal(39, converted.Value); + Assert.Equal(HowMuchUnit.Some, converted.Unit); + } + [Theory] [InlineData(1, HowMuchUnit.Some, HowMuchUnit.Some, 1)] [InlineData(1, HowMuchUnit.Some, HowMuchUnit.ATon, 2)] @@ -39,6 +121,18 @@ public void ConvertByName_ConvertsTheValueToGivenUnit(double expectedValue, doub Assert.Equal(expectedValue, UnitConverter.ConvertByName(inputValue, quantityTypeName, fromUnit, toUnit)); } + [Fact] + public void ConvertByName_QuantityCaseInsensitive() + { + Assert.Equal(0, UnitConverter.ConvertByName(0, "length", "Meter", "Centimeter")); + } + + [Fact] + public void ConvertByName_UnitTypeCaseInsensitive() + { + Assert.Equal(0, UnitConverter.ConvertByName(0, "Length", "meter", "Centimeter")); + } + [Theory] [InlineData(1, "UnknownQuantity", "Meter", "Centimeter")] public void ConvertByName_ThrowsUnitNotFoundExceptionOnUnknownQuantity(double inputValue, string quantityTypeName, string fromUnit, string toUnit) @@ -60,7 +154,7 @@ public void ConvertByName_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnit(doubl [InlineData(1, "Length", "Meter", "UnknownToUnit")] public void TryConvertByName_ReturnsFalseForInvalidInput(double inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.False(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out var result)); + Assert.False(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out double result)); Assert.Equal(0, result); } @@ -72,7 +166,7 @@ public void TryConvertByName_ReturnsFalseForInvalidInput(double inputValue, stri public void TryConvertByName_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.True(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out var result), "TryConvertByName() return value."); + Assert.True(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out double result), "TryConvertByName() return value."); Assert.Equal(expectedValue, result); } @@ -81,16 +175,14 @@ public void TryConvertByName_ReturnsTrueOnSuccessAndOutputsResult(double expecte [InlineData(100, 1, "Length", "m", "cm")] [InlineData(1, 1000, "Mass", "g", "kg")] [InlineData(1000, 1, "ElectricCurrent", "kA", "A")] - public void ConvertByAbbreviation_ConvertsTheValueToGivenUnit(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, - string toUnit) + public void ConvertByAbbreviation_ConvertsTheValueToGivenUnit(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit) { Assert.Equal(expectedValue, UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); } [Theory] [InlineData(1, "UnknownQuantity", "m", "cm")] - public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownQuantity(double inputValue, string quantityTypeName, string fromUnit, - string toUnit) + public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownQuantity( double inputValue, string quantityTypeName, string fromUnit, string toUnit) { Assert.Throws(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); } @@ -98,8 +190,7 @@ public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownQuantity(d [Theory] [InlineData(1, "Length", "UnknownFromUnit", "cm")] [InlineData(1, "Length", "m", "UnknownToUnit")] - public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnitAbbreviation(double inputValue, string quantityTypeName, - string fromUnit, string toUnit) + public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnitAbbreviation(double inputValue, string quantityTypeName, string fromUnit, string toUnit) { Assert.Throws(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); } @@ -110,7 +201,7 @@ public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUn [InlineData(1, "Length", "m", "UnknownToUnit")] public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(double inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out var result)); + Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out double result)); Assert.Equal(0, result); } @@ -119,123 +210,11 @@ public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(double inputVal [InlineData(100, 1, "Length", "m", "cm")] [InlineData(1, 1000, "Mass", "g", "kg")] [InlineData(1000, 1, "ElectricCurrent", "kA", "A")] - public void TryConvertByAbbreviation_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, - string fromUnit, + public void TryConvertByAbbreviation_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out var result), - "TryConvertByAbbreviation() return value."); + Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out double result), "TryConvertByAbbreviation() return value."); Assert.Equal(expectedValue, result); } - - [Fact] - public void ConversionToSameUnit_ReturnsSameQuantity() - { - var unitConverter = new UnitConverter(); - - var foundConversionFunction = unitConverter.GetConversionFunction(HowMuchUnit.ATon, HowMuchUnit.ATon); - var converted = foundConversionFunction(new HowMuch(39, - HowMuchUnit.Some)); // Intentionally pass the wrong unit here, to test that the exact same quantity is returned - - Assert.Equal(39, converted.Value); - Assert.Equal(HowMuchUnit.Some, converted.Unit); - } - - [Fact] - public void ConvertByName_QuantityCaseInsensitive() - { - Assert.Equal(0, UnitConverter.ConvertByName(0, "length", "Meter", "Centimeter")); - } - - [Fact] - public void ConvertByName_UnitTypeCaseInsensitive() - { - Assert.Equal(0, UnitConverter.ConvertByName(0, "Length", "meter", "Centimeter")); - } - - [Fact] - public void CustomConversionWithDifferentQuantityTypes() - { - IQuantity ConversionFunction(IQuantity from) - { - return Length.FromInches(18); - } - - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(MassUnit.Grain, LengthUnit.Inch, ConversionFunction); - - var foundConversionFunction = unitConverter.GetConversionFunction(MassUnit.Grain, LengthUnit.Inch); - var converted = foundConversionFunction(Mass.FromGrains(100)); - - Assert.Equal(Length.FromInches(18), converted); - } - - [Fact] - public void CustomConversionWithDifferentQuantityTypesByTypeParam() - { - IQuantity ConversionFunction(IQuantity from) - { - return Length.FromInches(18); - } - - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(MassUnit.Grain, LengthUnit.Inch, ConversionFunction); - - var foundConversionFunction = unitConverter.GetConversionFunction(typeof(Mass), MassUnit.Grain, typeof(Length), LengthUnit.Inch); - var converted = foundConversionFunction(Mass.FromGrains(100)); - - Assert.Equal(Length.FromInches(18), converted); - } - - [Fact] - public void CustomConversionWithSameQuantityType() - { - Length ConversionFunction(Length from) - { - return Length.FromInches(18); - } - - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, ConversionFunction); - - var foundConversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Inch); - var converted = foundConversionFunction(Length.FromMeters(1.0)); - - Assert.Equal(Length.FromInches(18), converted); - } - - [Fact] - public void CustomConversionWithSameQuantityTypeByTypeParam() - { - Length ConversionFunction(Length from) - { - return Length.FromInches(18); - } - - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, (ConversionFunction) ConversionFunction); - - var foundConversionFunction = unitConverter.GetConversionFunction(typeof(Length), LengthUnit.Meter, typeof(Length), LengthUnit.Inch); - var converted = foundConversionFunction(Length.FromMeters(1.0)); - - Assert.Equal(Length.FromInches(18), converted); - } - - [Fact] - public void TryCustomConversionForOilBarrelsToUsGallons() - { - Volume ConversionFunction(Volume from) - { - return Volume.FromUsGallons(from.Value * 42); - } - - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.UsGallon, ConversionFunction); - - var foundConversionFunction = unitConverter.GetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.UsGallon); - var converted = foundConversionFunction(Volume.FromOilBarrels(1)); - - Assert.Equal(Volume.FromUsGallons(42), converted); - } } } diff --git a/UnitsNet.Tests/UnitMathTests.cs b/UnitsNet.Tests/UnitMathTests.cs index 80a4e3f49b..affc38d44b 100644 --- a/UnitsNet.Tests/UnitMathTests.cs +++ b/UnitsNet.Tests/UnitMathTests.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; using System.Collections.Generic; using UnitsNet.Units; using Xunit; @@ -31,7 +28,7 @@ public void AverageOfLengthsCalculatesCorrectly() { var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; - var average = units.Average(LengthUnit.Centimeter); + Length average = units.Average(LengthUnit.Centimeter); Assert.Equal(75, average.Value); Assert.Equal(LengthUnit.Centimeter, average.Unit); @@ -40,7 +37,11 @@ public void AverageOfLengthsCalculatesCorrectly() [Fact] public void AverageOfLengthsWithNullSelectorThrowsException() { - var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; + var units = new[] + { + new KeyValuePair("1", Length.FromMeters(1)), + new KeyValuePair("2", Length.FromCentimeters(50)) + }; Assert.Throws(() => units.Average((Func, Length>) null, LengthUnit.Centimeter)); } @@ -48,9 +49,13 @@ public void AverageOfLengthsWithNullSelectorThrowsException() [Fact] public void AverageOfLengthsWithSelectorCalculatesCorrectly() { - var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; + var units = new[] + { + new KeyValuePair("1", Length.FromMeters(1)), + new KeyValuePair("2", Length.FromCentimeters(50)) + }; - var average = units.Average(x => x.Value, LengthUnit.Centimeter); + Length average = units.Average(x => x.Value, LengthUnit.Centimeter); Assert.Equal(75, average.Value); Assert.Equal(LengthUnit.Centimeter, average.Unit); @@ -77,7 +82,7 @@ public void MaxOfLengthsCalculatesCorrectly() { var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; - var max = units.Max(LengthUnit.Centimeter); + Length max = units.Max(LengthUnit.Centimeter); Assert.Equal(100, max.Value); Assert.Equal(LengthUnit.Centimeter, max.Unit); @@ -86,7 +91,11 @@ public void MaxOfLengthsCalculatesCorrectly() [Fact] public void MaxOfLengthsWithNullSelectorThrowsException() { - var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; + var units = new[] + { + new KeyValuePair("1", Length.FromMeters(1)), + new KeyValuePair("2", Length.FromCentimeters(50)) + }; Assert.Throws(() => units.Max((Func, Length>) null, LengthUnit.Centimeter)); } @@ -94,9 +103,13 @@ public void MaxOfLengthsWithNullSelectorThrowsException() [Fact] public void MaxOfLengthsWithSelectorCalculatesCorrectly() { - var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; + var units = new[] + { + new KeyValuePair("1", Length.FromMeters(1)), + new KeyValuePair("2", Length.FromCentimeters(50)) + }; - var max = units.Max(x => x.Value, LengthUnit.Centimeter); + Length max = units.Max(x => x.Value, LengthUnit.Centimeter); Assert.Equal(100, max.Value); Assert.Equal(LengthUnit.Centimeter, max.Unit); @@ -123,7 +136,7 @@ public void MinOfLengthsCalculatesCorrectly() { var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; - var min = units.Min(LengthUnit.Centimeter); + Length min = units.Min(LengthUnit.Centimeter); Assert.Equal(50, min.Value); Assert.Equal(LengthUnit.Centimeter, min.Unit); @@ -132,7 +145,11 @@ public void MinOfLengthsCalculatesCorrectly() [Fact] public void MinOfLengthsWithNullSelectorThrowsException() { - var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; + var units = new[] + { + new KeyValuePair("1", Length.FromMeters(1)), + new KeyValuePair("2", Length.FromCentimeters(50)) + }; Assert.Throws(() => units.Min((Func, Length>) null, LengthUnit.Centimeter)); } @@ -140,9 +157,13 @@ public void MinOfLengthsWithNullSelectorThrowsException() [Fact] public void MinOfLengthsWithSelectorCalculatesCorrectly() { - var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; + var units = new[] + { + new KeyValuePair("1", Length.FromMeters(1)), + new KeyValuePair("2", Length.FromCentimeters(50)) + }; - var min = units.Min(x => x.Value, LengthUnit.Centimeter); + Length min = units.Min(x => x.Value, LengthUnit.Centimeter); Assert.Equal(50, min.Value); Assert.Equal(LengthUnit.Centimeter, min.Unit); @@ -161,7 +182,7 @@ public void SumOfEmptySourceReturnsZero() { var units = new Length[] { }; - var sum = units.Sum(Length.BaseUnit); + Length sum = units.Sum(Length.BaseUnit); Assert.Equal(Length.Zero, sum); } @@ -171,7 +192,7 @@ public void SumOfLengthsCalculatesCorrectly() { var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; - var sum = units.Sum(LengthUnit.Centimeter); + Length sum = units.Sum(LengthUnit.Centimeter); Assert.Equal(150, sum.Value); Assert.Equal(LengthUnit.Centimeter, sum.Unit); @@ -180,7 +201,11 @@ public void SumOfLengthsCalculatesCorrectly() [Fact] public void SumOfLengthsWithNullSelectorThrowsException() { - var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; + var units = new[] + { + new KeyValuePair("1", Length.FromMeters(1)), + new KeyValuePair("2", Length.FromCentimeters(50)) + }; Assert.Throws(() => units.Sum((Func, Length>) null, LengthUnit.Centimeter)); } @@ -188,9 +213,13 @@ public void SumOfLengthsWithNullSelectorThrowsException() [Fact] public void SumOfLengthsWithSelectorCalculatesCorrectly() { - var units = new[] {new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50))}; + var units = new[] + { + new KeyValuePair("1", Length.FromMeters(1)), + new KeyValuePair("2", Length.FromCentimeters(50)) + }; - var sum = units.Sum(x => x.Value, LengthUnit.Centimeter); + Length sum = units.Sum(x => x.Value, LengthUnit.Centimeter); Assert.Equal(150, sum.Value); Assert.Equal(LengthUnit.Centimeter, sum.Unit); diff --git a/UnitsNet.Tests/UnitParserTests.cs b/UnitsNet.Tests/UnitParserTests.cs index 080449dbe5..08411f0a24 100644 --- a/UnitsNet.Tests/UnitParserTests.cs +++ b/UnitsNet.Tests/UnitParserTests.cs @@ -26,6 +26,43 @@ public void Parse_ReturnsUnitMappedByCustomAbbreviation(string customAbbreviatio Assert.Equal(expected, actual); } + [Fact] + public void Parse_AbbreviationCaseInsensitive_Lowercase_years() + { + var abbreviation = "years"; + var expected = DurationUnit.Year365; + var parser = UnitParser.Default; + + var actual = parser.Parse(abbreviation); + + Assert.Equal(expected, actual); + } + + [Fact] + public void Parse_AbbreviationCaseInsensitive_Uppercase_Years() + { + var abbreviation = "Years"; + var expected = DurationUnit.Year365; + var parser = UnitParser.Default; + + var actual = parser.Parse(abbreviation); + + Assert.Equal(expected, actual); + } + + [Fact] + public void Parse_GivenAbbreviationsThatAreAmbiguousWhenLowerCase_ReturnsCorrectUnit() + { + Assert.Equal(PressureUnit.Megabar, Pressure.ParseUnit("Mbar")); + Assert.Equal(PressureUnit.Millibar, Pressure.ParseUnit("mbar")); + } + + [Fact] + public void Parse_UnknownAbbreviationThrowsUnitNotFoundException() + { + Assert.Throws(() => UnitParser.Default.Parse("nonexistingunit")); + } + [Theory] [InlineData("m", typeof(LengthUnit), LengthUnit.Meter)] [InlineData("m^1", typeof(LengthUnit), LengthUnit.Meter)] @@ -63,42 +100,6 @@ public void Parse_CanParseWithWithspacesInUnit(string unitAbbreviation, Type uni Assert.Equal(resultUnitType, UnitParser.Default.Parse(unitAbbreviation, unitType)); } - [Theory] - [InlineData("ng", "en-US", MassUnit.Nanogram)] - [InlineData("нг", "ru-RU", MassUnit.Nanogram)] - [InlineData("g", "en-US", MassUnit.Gram)] - [InlineData("г", "ru-RU", MassUnit.Gram)] - [InlineData("kg", "en-US", MassUnit.Kilogram)] - [InlineData("кг", "ru-RU", MassUnit.Kilogram)] - public void ParseMassUnit_GivenCulture(string str, string cultureName, Enum expectedUnit) - { - Assert.Equal(expectedUnit, UnitParser.Default.Parse(str, new CultureInfo(cultureName))); - } - - [Fact] - public void Parse_AbbreviationCaseInsensitive_Lowercase_years() - { - var abbreviation = "years"; - var expected = DurationUnit.Year365; - var parser = UnitParser.Default; - - var actual = parser.Parse(abbreviation); - - Assert.Equal(expected, actual); - } - - [Fact] - public void Parse_AbbreviationCaseInsensitive_Uppercase_Years() - { - var abbreviation = "Years"; - var expected = DurationUnit.Year365; - var parser = UnitParser.Default; - - var actual = parser.Parse(abbreviation); - - Assert.Equal(expected, actual); - } - [Fact] public void Parse_AmbiguousUnitsThrowsException() { @@ -113,11 +114,16 @@ public void Parse_AmbiguousUnitsThrowsException() Assert.Equal("Cannot parse \"pt\" since it could be either of these: DtpPoint, PrinterPoint", exception2.Message); } - [Fact] - public void Parse_GivenAbbreviationsThatAreAmbiguousWhenLowerCase_ReturnsCorrectUnit() + [Theory] + [InlineData("ng", "en-US", MassUnit.Nanogram)] + [InlineData("нг", "ru-RU", MassUnit.Nanogram)] + [InlineData("g", "en-US", MassUnit.Gram)] + [InlineData("г", "ru-RU", MassUnit.Gram)] + [InlineData("kg", "en-US", MassUnit.Kilogram)] + [InlineData("кг", "ru-RU", MassUnit.Kilogram)] + public void ParseMassUnit_GivenCulture(string str, string cultureName, Enum expectedUnit) { - Assert.Equal(PressureUnit.Megabar, Pressure.ParseUnit("Mbar")); - Assert.Equal(PressureUnit.Millibar, Pressure.ParseUnit("mbar")); + Assert.Equal(expectedUnit, UnitParser.Default.Parse(str, new CultureInfo(cultureName))); } [Fact] @@ -131,11 +137,5 @@ public void Parse_MappedCustomUnit() Assert.Equal(HowMuchUnit.Some, parsedUnit); } - - [Fact] - public void Parse_UnknownAbbreviationThrowsUnitNotFoundException() - { - Assert.Throws(() => UnitParser.Default.Parse("nonexistingunit")); - } } } diff --git a/UnitsNet.Tests/UnitSystemTests.cs b/UnitsNet.Tests/UnitSystemTests.cs index ec44fb3367..b0da0923ca 100644 --- a/UnitsNet.Tests/UnitSystemTests.cs +++ b/UnitsNet.Tests/UnitSystemTests.cs @@ -9,28 +9,6 @@ namespace UnitsNet.Tests { public class UnitSystemTests { - [Theory] - [InlineData(LengthUnit.Undefined, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, - AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Undefined, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, - LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Undefined, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, - LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Undefined, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, - LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Undefined, AmountOfSubstanceUnit.Mole, - LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, - AmountOfSubstanceUnit.Undefined, LuminousIntensityUnit.Candela)] - [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, - LuminousIntensityUnit.Undefined)] - public void ConstructorThrowsArgumentExceptionWithUndefinedUnits(LengthUnit length, MassUnit mass, DurationUnit time, ElectricCurrentUnit current, - TemperatureUnit temperature, AmountOfSubstanceUnit amount, LuminousIntensityUnit luminousIntensity) - { - var baseUnits = new BaseUnits(length, mass, time, current, temperature, amount, luminousIntensity); - Assert.Throws(() => new UnitSystem(baseUnits)); - } - [Fact] public void ConstructorImplementedProperly() { @@ -48,8 +26,23 @@ public void ConstructorThrowsArgumentNullExceptionForNullBaseUnits() Assert.Throws(() => new UnitSystem(null)); } + [Theory] + [InlineData(LengthUnit.Undefined, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Undefined, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Undefined, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Undefined, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Undefined, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Undefined, LuminousIntensityUnit.Candela)] + [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Undefined)] + public void ConstructorThrowsArgumentExceptionWithUndefinedUnits(LengthUnit length, MassUnit mass, DurationUnit time, ElectricCurrentUnit current, + TemperatureUnit temperature, AmountOfSubstanceUnit amount, LuminousIntensityUnit luminousIntensity) + { + var baseUnits = new BaseUnits(length, mass, time, current, temperature, amount, luminousIntensity); + Assert.Throws(() => new UnitSystem(baseUnits)); + } + [Fact] - public void EqualityOperatorIsImplementedCorrectly() + public void EqualsObjectIsImplementedCorrectly() { var unitSystem1 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); @@ -60,23 +53,15 @@ public void EqualityOperatorIsImplementedCorrectly() var unitSystem3 = new UnitSystem(new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - Assert.True(unitSystem1 == unitSystem2); - Assert.True(unitSystem2 == unitSystem1); - - Assert.False(unitSystem1 == unitSystem3); - Assert.False(unitSystem3 == unitSystem1); - - Assert.False(unitSystem1 == null); - Assert.False(null == unitSystem1); - - UnitSystem nullUnitSystem1 = null; - UnitSystem nullUnitSystem2 = null; + Assert.True(unitSystem1.Equals((object)unitSystem2)); + Assert.False(unitSystem1.Equals((object)unitSystem3)); - Assert.True(nullUnitSystem1 == nullUnitSystem2); + Assert.False(unitSystem1.Equals("Some object.")); + Assert.False(unitSystem1.Equals((IFormatProvider)null)); } [Fact] - public void EqualsObjectIsImplementedCorrectly() + public void EqualsUnitSystemIsImplementedCorrectly() { var unitSystem1 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); @@ -87,15 +72,17 @@ public void EqualsObjectIsImplementedCorrectly() var unitSystem3 = new UnitSystem(new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - Assert.True(unitSystem1.Equals((object) unitSystem2)); - Assert.False(unitSystem1.Equals((object) unitSystem3)); + Assert.True(unitSystem1.Equals(unitSystem2)); + Assert.True(unitSystem2.Equals(unitSystem1)); - Assert.False(unitSystem1.Equals("Some object.")); - Assert.False(unitSystem1.Equals((IFormatProvider) null)); + Assert.False(unitSystem1.Equals(unitSystem3)); + Assert.False(unitSystem3.Equals(unitSystem1)); + + Assert.False(unitSystem1.Equals(null)); } [Fact] - public void EqualsUnitSystemIsImplementedCorrectly() + public void EqualityOperatorIsImplementedCorrectly() { var unitSystem1 = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); @@ -106,13 +93,19 @@ public void EqualsUnitSystemIsImplementedCorrectly() var unitSystem3 = new UnitSystem(new BaseUnits(LengthUnit.Foot, MassUnit.Pound, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.DegreeFahrenheit, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); - Assert.True(unitSystem1.Equals(unitSystem2)); - Assert.True(unitSystem2.Equals(unitSystem1)); + Assert.True(unitSystem1 == unitSystem2); + Assert.True(unitSystem2 == unitSystem1); - Assert.False(unitSystem1.Equals(unitSystem3)); - Assert.False(unitSystem3.Equals(unitSystem1)); + Assert.False(unitSystem1 == unitSystem3); + Assert.False(unitSystem3 == unitSystem1); - Assert.False(unitSystem1.Equals(null)); + Assert.False(unitSystem1 == null); + Assert.False(null == unitSystem1); + + UnitSystem nullUnitSystem1 = null; + UnitSystem nullUnitSystem2 = null; + + Assert.True(nullUnitSystem1 == nullUnitSystem2); } [Fact] diff --git a/UnitsNet/AssemblyInfo.cs b/UnitsNet/AssemblyInfo.cs index 4d58eaa273..d897374117 100644 --- a/UnitsNet/AssemblyInfo.cs +++ b/UnitsNet/AssemblyInfo.cs @@ -5,6 +5,5 @@ using System.Runtime.CompilerServices; [assembly: CLSCompliant(true)] -[assembly: - InternalsVisibleTo( - "UnitsNet.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010089abdcb0025f7d1c4c766686dd852b978ca5bb9fd80bba9d3539e8399b01170ae0ea10c0c3baa301b1d13090d5aff770532de00c88b67c4b24669fde7f9d87218f1c6c073a09016cbb2f87119b94227c2301f4e2a096043e30f7c47c872bbd8e0b80d924952e6b36990f13f847e83e9efb107ec2121fe39d7edaaa4e235af8c4")] +[assembly: InternalsVisibleTo("UnitsNet.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010089abdcb0025f7d1c4c766686dd852b978ca5bb9fd80bba9d3539e8399b01170ae0ea10c0c3baa301b1d13090d5aff770532de00c88b67c4b24669fde7f9d87218f1c6c073a09016cbb2f87119b94227c2301f4e2a096043e30f7c47c872bbd8e0b80d924952e6b36990f13f847e83e9efb107ec2121fe39d7edaaa4e235af8c4")] + diff --git a/UnitsNet/BaseDimensions.cs b/UnitsNet/BaseDimensions.cs index 4ceb5f9800..1b2f8c70ff 100644 --- a/UnitsNet/BaseDimensions.cs +++ b/UnitsNet/BaseDimensions.cs @@ -2,8 +2,8 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using System.Linq; using System.Text; +using System.Linq; namespace UnitsNet { @@ -25,58 +25,18 @@ public BaseDimensions(int length, int mass, int time, int current, int temperatu } /// - /// Gets the length dimensions (L). - /// - public int Length { get; } - - /// - /// Gets the mass dimensions (M). - /// - public int Mass { get; } - - /// - /// Gets the time dimensions (T). - /// - public int Time { get; } - - /// - /// Gets the electric current dimensions (I). - /// - public int Current { get; } - - /// - /// Gets the temperature dimensions (Θ). - /// - public int Temperature { get; } - - /// - /// Gets the amount of substance dimensions (N). - /// - public int Amount { get; } - - /// - /// Gets the luminous intensity dimensions (J). - /// - public int LuminousIntensity { get; } - - /// - /// Represents a dimensionless (unitless) quantity. - /// - public static BaseDimensions Dimensionless { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 0); - - /// - /// Checks if the dimensions represent a base quantity. + /// Checks if the dimensions represent a base quantity. /// /// True if the dimensions represent a base quantity, otherwise false. public bool IsBaseQuantity() { - var dimensionsArray = new[] {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}; - var onlyOneEqualsOne = dimensionsArray.Where(dimension => dimension == 1).Take(2).Count() == 1; + var dimensionsArray = new int[]{Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}; + bool onlyOneEqualsOne = dimensionsArray.Where(dimension => dimension == 1).Take(2).Count() == 1; return onlyOneEqualsOne; } /// - /// Checks if the dimensions represent a derived quantity. + /// Checks if the dimensions represent a derived quantity. /// /// True if the dimensions represent a derived quantity, otherwise false. public bool IsDerivedQuantity() @@ -85,7 +45,7 @@ public bool IsDerivedQuantity() } /// - /// Checks if this base dimensions object represents a dimensionless quantity. + /// Checks if this base dimensions object represents a dimensionless quantity. /// /// True if this object represents a dimensionless quantity, otherwise false. public bool IsDimensionless() @@ -96,48 +56,35 @@ public bool IsDimensionless() /// public override bool Equals(object obj) { - if (obj is null || !(obj is BaseDimensions)) - { + if(obj is null || !(obj is BaseDimensions)) return false; - } - var other = (BaseDimensions) obj; + var other = (BaseDimensions)obj; return Length == other.Length && - Mass == other.Mass && - Time == other.Time && - Current == other.Current && - Temperature == other.Temperature && - Amount == other.Amount && - LuminousIntensity == other.LuminousIntensity; + Mass == other.Mass && + Time == other.Time && + Current == other.Current && + Temperature == other.Temperature && + Amount == other.Amount && + LuminousIntensity == other.LuminousIntensity; } /// public override int GetHashCode() { - return new - { - Length, - Mass, - Time, - Current, - Temperature, - Amount, - LuminousIntensity - }.GetHashCode(); + return new {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}.GetHashCode(); } /// - /// Get resulting dimensions after multiplying two dimensions, by performing addition of each dimension. + /// Get resulting dimensions after multiplying two dimensions, by performing addition of each dimension. /// /// Other dimensions. /// Resulting dimensions. public BaseDimensions Multiply(BaseDimensions right) { - if (right is null) - { + if(right is null) throw new ArgumentNullException(nameof(right)); - } return new BaseDimensions( Length + right.Length, @@ -150,16 +97,14 @@ public BaseDimensions Multiply(BaseDimensions right) } /// - /// Get resulting dimensions after dividing two dimensions, by performing subtraction of each dimension. + /// Get resulting dimensions after dividing two dimensions, by performing subtraction of each dimension. /// /// Other dimensions. /// Resulting dimensions. public BaseDimensions Divide(BaseDimensions right) { - if (right is null) - { + if(right is null) throw new ArgumentNullException(nameof(right)); - } return new BaseDimensions( Length - right.Length, @@ -172,7 +117,7 @@ public BaseDimensions Divide(BaseDimensions right) } /// - /// Check if two dimensions are equal. + /// Check if two dimensions are equal. /// /// Left. /// Right. @@ -183,7 +128,7 @@ public BaseDimensions Divide(BaseDimensions right) } /// - /// Check if two dimensions are unequal. + /// Check if two dimensions are unequal. /// /// Left. /// Right. @@ -194,43 +139,33 @@ public BaseDimensions Divide(BaseDimensions right) } /// - /// Multiply two dimensions. + /// Multiply two dimensions. /// /// Left. /// Right. /// Resulting dimensions. public static BaseDimensions operator *(BaseDimensions left, BaseDimensions right) { - if (left is null) - { + if(left is null) throw new ArgumentNullException(nameof(left)); - } - - if (right is null) - { + else if(right is null) throw new ArgumentNullException(nameof(right)); - } return left.Multiply(right); } /// - /// Divide two dimensions. + /// Divide two dimensions. /// /// Left. /// Right. /// Resulting dimensions. public static BaseDimensions operator /(BaseDimensions left, BaseDimensions right) { - if (left is null) - { + if(left is null) throw new ArgumentNullException(nameof(left)); - } - - if (right is null) - { + else if(right is null) throw new ArgumentNullException(nameof(right)); - } return left.Divide(right); } @@ -255,15 +190,53 @@ private static void AppendDimensionString(StringBuilder sb, string name, int val { var absoluteValue = Math.Abs(value); - if (absoluteValue > 0) + if(absoluteValue > 0) { sb.AppendFormat("[{0}]", name); - if (absoluteValue > 1) - { + if(absoluteValue > 1) sb.AppendFormat("^{0}", value); - } } } + + /// + /// Gets the length dimensions (L). + /// + public int Length { get; } + + /// + /// Gets the mass dimensions (M). + /// + public int Mass{ get; } + + /// + /// Gets the time dimensions (T). + /// + public int Time{ get; } + + /// + /// Gets the electric current dimensions (I). + /// + public int Current{ get; } + + /// + /// Gets the temperature dimensions (Θ). + /// + public int Temperature{ get; } + + /// + /// Gets the amount of substance dimensions (N). + /// + public int Amount{ get; } + + /// + /// Gets the luminous intensity dimensions (J). + /// + public int LuminousIntensity{ get; } + + /// + /// Represents a dimensionless (unitless) quantity. + /// + public static BaseDimensions Dimensionless { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 0); } } diff --git a/UnitsNet/BaseUnits.cs b/UnitsNet/BaseUnits.cs index 0b1cc5f971..cfcf559eb1 100644 --- a/UnitsNet/BaseUnits.cs +++ b/UnitsNet/BaseUnits.cs @@ -12,11 +12,16 @@ namespace UnitsNet /// Represents the base units for a quantity. All quantities, both base and derived, can be /// represented by a combination of these seven base units. /// - public sealed class BaseUnits : IEquatable + public sealed class BaseUnits: IEquatable { /// - /// Creates an instance of if the base units class that represents the base units for a quantity. - /// All quantities, both base and derived, can be represented by a combination of these seven base units. + /// Represents BaseUnits that have not been defined. + /// + public static BaseUnits Undefined { get; } = new BaseUnits(); + + /// + /// Creates an instance of if the base units class that represents the base units for a quantity. + /// All quantities, both base and derived, can be represented by a combination of these seven base units. /// /// The length unit (L). /// The mass unit (M). @@ -43,154 +48,92 @@ public BaseUnits( LuminousIntensity = luminousIntensity; IsFullyDefined = Length != LengthUnit.Undefined && - Mass != MassUnit.Undefined && - Time != DurationUnit.Undefined && - Current != ElectricCurrentUnit.Undefined && - Temperature != TemperatureUnit.Undefined && - Amount != AmountOfSubstanceUnit.Undefined && - LuminousIntensity != LuminousIntensityUnit.Undefined; + Mass != MassUnit.Undefined && + Time != DurationUnit.Undefined && + Current != ElectricCurrentUnit.Undefined && + Temperature != TemperatureUnit.Undefined && + Amount != AmountOfSubstanceUnit.Undefined && + LuminousIntensity != LuminousIntensityUnit.Undefined; } - /// - /// Represents BaseUnits that have not been defined. - /// - public static BaseUnits Undefined { get; } = new BaseUnits(); - - /// - /// Gets the length unit (L). - /// - public LengthUnit Length { get; } - - /// - /// Gets the mass unit (M). - /// - public MassUnit Mass { get; } - - /// - /// Gets the time unit (T). - /// - public DurationUnit Time { get; } - - /// - /// Gets the electric current unit (I). - /// - public ElectricCurrentUnit Current { get; } - - /// - /// Gets the temperature unit (Θ). - /// - public TemperatureUnit Temperature { get; } - - /// - /// Gets the amount of substance unit (N). - /// - public AmountOfSubstanceUnit Amount { get; } - - /// - /// Gets the luminous intensity unit (J). - /// - public LuminousIntensityUnit LuminousIntensity { get; } + /// + public override bool Equals(object obj) + { + if(obj is null || !(obj is BaseUnits)) + return false; - /// - /// Gets whether or not all of the base units are defined. - /// - public bool IsFullyDefined { get; } + return Equals((BaseUnits)obj); + } /// - /// Checks if all of the base units are equal to another instance's. + /// Checks if all of the base units are equal to another instance's. /// /// The other instance to check if equal to. /// True if equal, otherwise false. public bool Equals(BaseUnits other) { - if (other is null) - { + if(other is null) return false; - } return Length == other.Length && - Mass == other.Mass && - Time == other.Time && - Current == other.Current && - Temperature == other.Temperature && - Amount == other.Amount && - LuminousIntensity == other.LuminousIntensity; - } - - /// - public override bool Equals(object obj) - { - if (obj is null || !(obj is BaseUnits)) - { - return false; - } - - return Equals((BaseUnits) obj); + Mass == other.Mass && + Time == other.Time && + Current == other.Current && + Temperature == other.Temperature && + Amount == other.Amount && + LuminousIntensity == other.LuminousIntensity; } /// - /// Checks if the base units are a subset of another. Undefined base units are ignored. - /// If all base united are undefined (equal to ), - /// IsSubsetOf will return true only if other is also equal to . + /// Checks if the base units are a subset of another. Undefined base units are ignored. + /// If all base united are undefined (equal to ), + /// IsSubsetOf will return true only if other is also equal to . /// - /// The other to compare to. + /// The other to compare to. /// True if the base units are a subset of other, otherwise false. public bool IsSubsetOf(BaseUnits other) { - if (other is null) - { + if(other is null) return false; - } // If all base units are undefined, can only be a subset of another where all base units are undefined. - if (Equals(Undefined)) - { + if(Equals(Undefined)) return other.Equals(Undefined); - } return (Length == LengthUnit.Undefined || Length == other.Length) && - (Mass == MassUnit.Undefined || Mass == other.Mass) && - (Time == DurationUnit.Undefined || Time == other.Time) && - (Current == ElectricCurrentUnit.Undefined || Current == other.Current) && - (Temperature == TemperatureUnit.Undefined || Temperature == other.Temperature) && - (Amount == AmountOfSubstanceUnit.Undefined || Amount == other.Amount) && - (LuminousIntensity == LuminousIntensityUnit.Undefined || LuminousIntensity == other.LuminousIntensity); + (Mass == MassUnit.Undefined || Mass == other.Mass) && + (Time == DurationUnit.Undefined || Time == other.Time) && + (Current == ElectricCurrentUnit.Undefined || Current == other.Current) && + (Temperature == TemperatureUnit.Undefined || Temperature == other.Temperature) && + (Amount == AmountOfSubstanceUnit.Undefined || Amount == other.Amount) && + (LuminousIntensity == LuminousIntensityUnit.Undefined || LuminousIntensity == other.LuminousIntensity); } /// public override int GetHashCode() { - return new - { - Length, - Mass, - Time, - Current, - Temperature, - Amount, - LuminousIntensity - }.GetHashCode(); + return new {Length, Mass, Time, Current, Temperature, Amount, LuminousIntensity}.GetHashCode(); } /// - /// Checks if this instance is equal to another. + /// Checks if this instance is equal to another. /// /// The left instance. /// The right instance. /// True if equal, otherwise false. - /// + /// public static bool operator ==(BaseUnits left, BaseUnits right) { return left is null ? right is null : left.Equals(right); } /// - /// Checks if this instance is not equal to another. + /// Checks if this instance is not equal to another. /// /// The left instance. /// The right instance. /// True if not equal, otherwise false. - /// + /// public static bool operator !=(BaseUnits left, BaseUnits right) { return !(left == right); @@ -211,5 +154,45 @@ public override string ToString() return sb.ToString(); } + + /// + /// Gets the length unit (L). + /// + public LengthUnit Length { get; } + + /// + /// Gets the mass unit (M). + /// + public MassUnit Mass{ get; } + + /// + /// Gets the time unit (T). + /// + public DurationUnit Time{ get; } + + /// + /// Gets the electric current unit (I). + /// + public ElectricCurrentUnit Current{ get; } + + /// + /// Gets the temperature unit (Θ). + /// + public TemperatureUnit Temperature{ get; } + + /// + /// Gets the amount of substance unit (N). + /// + public AmountOfSubstanceUnit Amount{ get; } + + /// + /// Gets the luminous intensity unit (J). + /// + public LuminousIntensityUnit LuminousIntensity{ get; } + + /// + /// Gets whether or not all of the base units are defined. + /// + public bool IsFullyDefined { get; } } } diff --git a/UnitsNet/Comparison.cs b/UnitsNet/Comparison.cs index a1175dd1cc..575707e6b5 100644 --- a/UnitsNet/Comparison.cs +++ b/UnitsNet/Comparison.cs @@ -52,9 +52,7 @@ public static class Comparison public static bool Equals(double referenceValue, double otherValue, double tolerance, ComparisonType comparisonType) { if (tolerance < 0) - { throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); - } switch (comparisonType) { @@ -91,9 +89,7 @@ public static bool Equals(double referenceValue, double otherValue, double toler public static bool EqualsRelative(double referenceValue, double otherValue, double tolerance) { if (tolerance < 0) - { throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); - } var maxVariation = Math.Abs(referenceValue * tolerance); return Math.Abs(referenceValue - otherValue) <= maxVariation; @@ -121,9 +117,7 @@ public static bool EqualsRelative(double referenceValue, double otherValue, doub public static bool EqualsAbsolute(double value1, double value2, double tolerance) { if (tolerance < 0) - { throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0"); - } return Math.Abs(value1 - value2) <= tolerance; } diff --git a/UnitsNet/ComparisonType.cs b/UnitsNet/ComparisonType.cs index 152ef294d7..18f76cfdd3 100644 --- a/UnitsNet/ComparisonType.cs +++ b/UnitsNet/ComparisonType.cs @@ -4,17 +4,17 @@ namespace UnitsNet { /// - /// Specifies if the comparison between numbers is absolute or relative. + /// Specifies if the comparison between numbers is absolute or relative. /// public enum ComparisonType { /// - /// Error margin in relative size to a reference value. + /// Error margin in relative size to a reference value. /// Relative, /// - /// Error margin as absolute size. + /// Error margin as absolute size. /// Absolute } diff --git a/UnitsNet/CustomCode/GlobalConfiguration.cs b/UnitsNet/CustomCode/GlobalConfiguration.cs index f08345870d..746e98dc65 100644 --- a/UnitsNet/CustomCode/GlobalConfiguration.cs +++ b/UnitsNet/CustomCode/GlobalConfiguration.cs @@ -16,7 +16,7 @@ namespace UnitsNet public static class GlobalConfiguration { /// - /// Wrapper for . + /// Wrapper for . /// [Obsolete("Manipulate Thread.CurrentThread.CurrentUICulture instead, this property will be removed.")] public static IFormatProvider DefaultCulture diff --git a/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs b/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs index 4df4832f72..75a2eba9cf 100644 --- a/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Acceleration.extra.cs @@ -1,18 +1,16 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using UnitsNet.Units; - namespace UnitsNet { public partial struct Acceleration { /// - /// Multiply and to get . + /// Multiply and to get . /// public static SpecificWeight operator *(Acceleration acceleration, Density density) { - return new SpecificWeight(acceleration.MetersPerSecondSquared * density.KilogramsPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter); + return new SpecificWeight(acceleration.MetersPerSecondSquared * density.KilogramsPerCubicMeter, UnitsNet.Units.SpecificWeightUnit.NewtonPerCubicMeter); } } } diff --git a/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs b/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs index 2689919638..30693f48eb 100644 --- a/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs @@ -10,27 +10,22 @@ namespace UnitsNet public partial struct AmountOfSubstance { /// - /// The Avogadro constant is the number of constituent particles, usually molecules, - /// atoms or ions that are contained in the amount of substance given by one mole. It is the proportionality factor - /// that relates - /// the molar mass of a substance to the mass of a sample, is designated with the symbol NA or L[1], and has the value + /// The Avogadro constant is the number of constituent particles, usually molecules, + /// atoms or ions that are contained in the amount of substance given by one mole. It is the proportionality factor that relates + /// the molar mass of a substance to the mass of a sample, is designated with the symbol NA or L[1], and has the value /// 6.02214076e23 mol−1 in the International System of Units (SI). /// /// - /// Pending revisions in the base set of SI units necessitated redefinitions of the concepts of chemical quantity. The - /// Avogadro number, - /// and its definition, was deprecated in favor of the Avogadro constant and its definition. Based on measurements made - /// through the - /// middle of 2017 which calculated a value for the Avogadro constant of NA = 6.022140758(62)×1023 mol−1, the - /// redefinition of SI units + /// Pending revisions in the base set of SI units necessitated redefinitions of the concepts of chemical quantity. The Avogadro number, + /// and its definition, was deprecated in favor of the Avogadro constant and its definition. Based on measurements made through the + /// middle of 2017 which calculated a value for the Avogadro constant of NA = 6.022140758(62)×1023 mol−1, the redefinition of SI units /// is planned to take effect on 20 May 2019. The value of the constant will be fixed to exactly 6.02214076×1023 mol−1. /// See here: https://www.bipm.org/utils/common/pdf/CGPM-2018/26th-CGPM-Resolutions.pdf /// public static double AvogadroConstant { get; } = 6.02214076e23; /// - /// Calculates the number of particles (atoms or molecules) in this amount of substance using the - /// . + /// Calculates the number of particles (atoms or molecules) in this amount of substance using the . /// /// The number of particles (atoms or molecules) in this amount of substance. public double NumberOfParticles() @@ -45,7 +40,7 @@ public static AmountOfSubstance FromMass(Mass mass, MolarMass molarMass) { return mass / molarMass; } - + /// Get from for a given . public static Mass operator *(AmountOfSubstance amountOfSubstance, MolarMass molarMass) { @@ -69,5 +64,6 @@ public static AmountOfSubstance FromMass(Mass mass, MolarMass molarMass) { return Volume.FromCubicMeters(amountOfSubstance.Moles / molarity.MolesPerCubicMeter); } + } } diff --git a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs index b494ce8e4a..cc0a3cfcdf 100644 --- a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs @@ -19,11 +19,9 @@ public AmplitudeRatio(ElectricPotential voltage) : this() { if (voltage.Volts <= 0) - { throw new ArgumentOutOfRangeException( nameof(voltage), "The base-10 logarithm of a number ≤ 0 is undefined. Voltage must be greater than 0 V."); - } // E(dBV) = 20*log10(value(V)/reference(V)) _value = 20 * Math.Log10(voltage.Volts / 1); @@ -42,7 +40,7 @@ public AmplitudeRatio(ElectricPotential voltage) public ElectricPotential ToElectricPotential() { // E(V) = 1V * 10^(E(dBV)/20) - return ElectricPotential.FromVolts(Math.Pow(10, DecibelVolts / 20)); + return ElectricPotential.FromVolts( Math.Pow( 10, DecibelVolts / 20 ) ); } /// @@ -50,10 +48,10 @@ public ElectricPotential ToElectricPotential() /// /// The input impedance of the load. This is usually 50, 75 or 600 ohms. /// http://www.maximintegrated.com/en/app-notes/index.mvp/id/808 - public PowerRatio ToPowerRatio(ElectricResistance impedance) + public PowerRatio ToPowerRatio( ElectricResistance impedance ) { // P(dBW) = E(dBV) - 10*log10(Z(Ω)/1) - return PowerRatio.FromDecibelWatts(DecibelVolts - 10 * Math.Log10(impedance.Ohms / 1)); + return PowerRatio.FromDecibelWatts( DecibelVolts - 10 * Math.Log10( impedance.Ohms / 1 ) ); } #region Static Methods diff --git a/UnitsNet/CustomCode/Quantities/Angle.extra.cs b/UnitsNet/CustomCode/Quantities/Angle.extra.cs index 7b64e742b1..59318915c4 100644 --- a/UnitsNet/CustomCode/Quantities/Angle.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Angle.extra.cs @@ -7,7 +7,7 @@ namespace UnitsNet { public partial struct Angle { - /// Get from delta over time delta. + /// Get from delta over time delta. public static RotationalSpeed operator /(Angle angle, TimeSpan timeSpan) { return RotationalSpeed.FromRadiansPerSecond(angle.Radians / timeSpan.TotalSeconds); diff --git a/UnitsNet/CustomCode/Quantities/Area.extra.cs b/UnitsNet/CustomCode/Quantities/Area.extra.cs index 6bcb0696fa..a4c005015c 100644 --- a/UnitsNet/CustomCode/Quantities/Area.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Area.extra.cs @@ -24,19 +24,19 @@ public static Area FromCircleRadius(Length radius) #endregion - /// Get from divided by . + /// Get from divided by . public static Length operator /(Area area, Length length) { return Length.FromMeters(area.SquareMeters / length.Meters); } - /// Get from times . + /// Get from times . public static MassFlow operator *(Area area, MassFlux massFlux) { return MassFlow.FromGramsPerSecond(area.SquareMeters * massFlux.GramsPerSecondPerSquareMeter); } - /// Get from times . + /// Get from times . public static VolumeFlow operator *(Area area, Speed speed) { return VolumeFlow.FromCubicMetersPerSecond(area.SquareMeters * speed.MetersPerSecond); diff --git a/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs b/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs index 65545160af..6afa77213e 100644 --- a/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AreaMomentOfInertia.extra.cs @@ -1,11 +1,13 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using System; + namespace UnitsNet { public partial struct AreaMomentOfInertia { - /// Get from divided by . + /// Get from divided by . public static Volume operator /(AreaMomentOfInertia areaMomentOfInertia, Length length) { return Volume.FromCubicMeters(areaMomentOfInertia.MetersToTheFourth / length.Meters); diff --git a/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs b/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs index a8f3b6479f..5bd29a877a 100644 --- a/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs +++ b/UnitsNet/CustomCode/Quantities/BrakeSpecificFuelConsumption.extra.cs @@ -5,25 +5,22 @@ namespace UnitsNet { public partial struct BrakeSpecificFuelConsumption { - /// Get from times . + /// Get from times . public static MassFlow operator *(BrakeSpecificFuelConsumption bsfc, Power power) { - return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule * power.Watts); + return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule*power.Watts); } - /// - /// Get from divided by - /// . - /// + /// Get from divided by . public static SpecificEnergy operator /(double value, BrakeSpecificFuelConsumption bsfc) { - return SpecificEnergy.FromJoulesPerKilogram(value / bsfc.KilogramsPerJoule); + return SpecificEnergy.FromJoulesPerKilogram(value/bsfc.KilogramsPerJoule); } - /// Get constant from times . + /// Get constant from times . public static double operator *(BrakeSpecificFuelConsumption bsfc, SpecificEnergy specificEnergy) { - return specificEnergy.JoulesPerKilogram * bsfc.KilogramsPerJoule; + return specificEnergy.JoulesPerKilogram*bsfc.KilogramsPerJoule; } } } diff --git a/UnitsNet/CustomCode/Quantities/Density.extra.cs b/UnitsNet/CustomCode/Quantities/Density.extra.cs index ad4514df59..e569cefac5 100644 --- a/UnitsNet/CustomCode/Quantities/Density.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Density.extra.cs @@ -12,7 +12,7 @@ public partial struct Density /// Gets from this . /// /// - /// + /// [Obsolete("This method is deprecated in favor of MassConcentration.ToMolarity(MolarMass).")] public Molarity ToMolarity(Mass molecularWeight) { @@ -24,7 +24,7 @@ public Molarity ToMolarity(Mass molecularWeight) /// /// Get from . /// - /// + /// [Obsolete("This method is deprecated in favor of MassConcentration.FromMolarity(Molarity, MolarMass).")] public static Density FromMolarity(Molarity molarity, Mass molecularWeight) { @@ -33,38 +33,38 @@ public static Density FromMolarity(Molarity molarity, Mass molecularWeight) #endregion - /// Get from times . + /// Get from times . public static Mass operator *(Density density, Volume volume) { return Mass.FromKilograms(density.KilogramsPerCubicMeter * volume.CubicMeters); } - /// Get from times . + /// Get from times . public static Mass operator *(Volume volume, Density density) { return Mass.FromKilograms(density.KilogramsPerCubicMeter * volume.CubicMeters); } - /// Get from times . + /// Get from times . public static DynamicViscosity operator *(Density density, KinematicViscosity kinematicViscosity) { return DynamicViscosity.FromNewtonSecondsPerMeterSquared(kinematicViscosity.SquareMetersPerSecond * density.KilogramsPerCubicMeter); } - /// Get times . + /// Get times . public static MassFlux operator *(Density density, Speed speed) { return MassFlux.FromKilogramsPerSecondPerSquareMeter(density.KilogramsPerCubicMeter * speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static SpecificWeight operator *(Density density, Acceleration acceleration) { return new SpecificWeight(density.KilogramsPerCubicMeter * acceleration.MetersPerSecondSquared, SpecificWeightUnit.NewtonPerCubicMeter); } - /// Get from divided by . - /// + /// Get from divided by . + /// [Obsolete("This operator is deprecated in favor of MassConcentration.op_Division(MassConcentration, MolarMass).")] public static Molarity operator /(Density density, Mass molecularWeight) { diff --git a/UnitsNet/CustomCode/Quantities/Duration.extra.cs b/UnitsNet/CustomCode/Quantities/Duration.extra.cs index c849e9fde9..61501525a0 100644 --- a/UnitsNet/CustomCode/Quantities/Duration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Duration.extra.cs @@ -14,88 +14,85 @@ public partial struct Duration /// The TimeSpan with the same time as the duration public TimeSpan ToTimeSpan() { - if (Seconds > TimeSpan.MaxValue.TotalSeconds || - Seconds < TimeSpan.MinValue.TotalSeconds) - { - throw new ArgumentOutOfRangeException(nameof(Duration), "The duration is too large or small to fit in a TimeSpan"); - } - - return TimeSpan.FromSeconds(Seconds); + if( Seconds > TimeSpan.MaxValue.TotalSeconds || + Seconds < TimeSpan.MinValue.TotalSeconds ) + throw new ArgumentOutOfRangeException( nameof( Duration ), "The duration is too large or small to fit in a TimeSpan" ); + return TimeSpan.FromSeconds( Seconds ); } - /// Get from plus . + /// Get from plus . public static DateTime operator +(DateTime time, Duration duration) { return time.AddSeconds(duration.Seconds); } - /// Get from minus . + /// Get from minus . public static DateTime operator -(DateTime time, Duration duration) { return time.AddSeconds(-duration.Seconds); } - /// Explicitly cast to . + /// Explicitly cast to . public static explicit operator TimeSpan(Duration duration) { return duration.ToTimeSpan(); } - /// Explicitly cast to . + /// Explicitly cast to . public static explicit operator Duration(TimeSpan duration) { return FromSeconds(duration.TotalSeconds); } - /// True if is less than . + /// True if is less than . public static bool operator <(Duration duration, TimeSpan timeSpan) { return duration.Seconds < timeSpan.TotalSeconds; } - /// True if is greater than . + /// True if is greater than . public static bool operator >(Duration duration, TimeSpan timeSpan) { return duration.Seconds > timeSpan.TotalSeconds; } - /// True if is less than or equal to . + /// True if is less than or equal to . public static bool operator <=(Duration duration, TimeSpan timeSpan) { return duration.Seconds <= timeSpan.TotalSeconds; } - /// True if is greater than or equal to . + /// True if is greater than or equal to . public static bool operator >=(Duration duration, TimeSpan timeSpan) { return duration.Seconds >= timeSpan.TotalSeconds; } - /// True if is less than . + /// True if is less than . public static bool operator <(TimeSpan timeSpan, Duration duration) { return timeSpan.TotalSeconds < duration.Seconds; } - /// True if is greater than . + /// True if is greater than . public static bool operator >(TimeSpan timeSpan, Duration duration) { return timeSpan.TotalSeconds > duration.Seconds; } - /// True if is less than or equal to . + /// True if is less than or equal to . public static bool operator <=(TimeSpan timeSpan, Duration duration) { return timeSpan.TotalSeconds <= duration.Seconds; } - /// True if is greater than or equal to . + /// True if is greater than or equal to . public static bool operator >=(TimeSpan timeSpan, Duration duration) { return timeSpan.TotalSeconds >= duration.Seconds; } - /// Get from times . + /// Get from times . public static Volume operator *(Duration duration, VolumeFlow volumeFlow) { return Volume.FromCubicMeters(volumeFlow.CubicMetersPerSecond * duration.Seconds); diff --git a/UnitsNet/CustomCode/Quantities/DynamicViscosity.extra.cs b/UnitsNet/CustomCode/Quantities/DynamicViscosity.extra.cs index 6c11f685e2..e99348a111 100644 --- a/UnitsNet/CustomCode/Quantities/DynamicViscosity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/DynamicViscosity.extra.cs @@ -5,7 +5,7 @@ namespace UnitsNet { public partial struct DynamicViscosity { - /// Get from divided by . + /// Get from divided by . public static KinematicViscosity operator /(DynamicViscosity dynamicViscosity, Density density) { return KinematicViscosity.FromSquareMetersPerSecond(dynamicViscosity.NewtonSecondsPerMeterSquared / density.KilogramsPerCubicMeter); diff --git a/UnitsNet/CustomCode/Quantities/ElectricCurrent.extra.cs b/UnitsNet/CustomCode/Quantities/ElectricCurrent.extra.cs index dddb95a2e6..261edea0c2 100644 --- a/UnitsNet/CustomCode/Quantities/ElectricCurrent.extra.cs +++ b/UnitsNet/CustomCode/Quantities/ElectricCurrent.extra.cs @@ -5,10 +5,7 @@ namespace UnitsNet { public partial struct ElectricCurrent { - /// - /// Get from multiplied by - /// . - /// + /// Get from multiplied by . /// Ohm's law implementation public static ElectricPotential operator *(ElectricCurrent current, ElectricResistance resistance) { diff --git a/UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs b/UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs index c0ef93827a..78e15c5fd8 100644 --- a/UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs +++ b/UnitsNet/CustomCode/Quantities/ElectricPotential.extra.cs @@ -6,8 +6,7 @@ namespace UnitsNet public partial struct ElectricPotential { /// - /// Gets an in decibels (dB) relative to 1 volt RMS from this - /// . + /// Gets an in decibels (dB) relative to 1 volt RMS from this . /// /// /// Provides a nicer syntax for converting a voltage to an amplitude ratio (relative to 1 volt RMS). @@ -20,20 +19,14 @@ public AmplitudeRatio ToAmplitudeRatio() return AmplitudeRatio.FromElectricPotential(this); } - /// - /// Get from divided by - /// . - /// + /// Get from divided by . /// Ohm's law implementation public static ElectricResistance operator /(ElectricPotential potential, ElectricCurrent current) { return ElectricResistance.FromOhms(potential.Volts / current.Amperes); } - /// - /// Get from divided by - /// . - /// + /// Get from divided by . /// Ohm's law implementation public static ElectricCurrent operator /(ElectricPotential potential, ElectricResistance resistance) { diff --git a/UnitsNet/CustomCode/Quantities/ElectricResistance.extra.cs b/UnitsNet/CustomCode/Quantities/ElectricResistance.extra.cs index 4f64e6ec9b..95d103d89e 100644 --- a/UnitsNet/CustomCode/Quantities/ElectricResistance.extra.cs +++ b/UnitsNet/CustomCode/Quantities/ElectricResistance.extra.cs @@ -5,10 +5,7 @@ namespace UnitsNet { public partial struct ElectricResistance { - /// - /// Get from multiplied by - /// . - /// + /// Get from multiplied by . /// Ohm's law implementation public static ElectricPotential operator *(ElectricResistance resistance, ElectricCurrent current) { diff --git a/UnitsNet/CustomCode/Quantities/Force.extra.cs b/UnitsNet/CustomCode/Quantities/Force.extra.cs index 372caccc06..1d9881edff 100644 --- a/UnitsNet/CustomCode/Quantities/Force.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Force.extra.cs @@ -7,50 +7,50 @@ namespace UnitsNet { public partial struct Force { - /// Get from divided by . + /// Get from divided by . public static Force FromPressureByArea(Pressure p, Area area) { - var newtons = p.Pascals * area.SquareMeters; + double newtons = p.Pascals * area.SquareMeters; return new Force(newtons, ForceUnit.Newton); } - /// Get from times . + /// Get from times . public static Force FromMassByAcceleration(Mass mass, Acceleration acceleration) { return new Force(mass.Kilograms * acceleration.MetersPerSecondSquared, ForceUnit.Newton); } - /// Get from times . + /// Get from times . public static Power operator *(Force force, Speed speed) { return Power.FromWatts(force.Newtons * speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static Power operator *(Speed speed, Force force) { return Power.FromWatts(force.Newtons * speed.MetersPerSecond); } - /// Get from divided by . + /// Get from divided by . public static Acceleration operator /(Force force, Mass mass) { return Acceleration.FromMetersPerSecondSquared(force.Newtons / mass.Kilograms); } - /// Get from divided by . + /// Get from divided by . public static Mass operator /(Force force, Acceleration acceleration) { return Mass.FromKilograms(force.Newtons / acceleration.MetersPerSecondSquared); } - /// Get from divided by . + /// Get from divided by . public static Pressure operator /(Force force, Area area) { return Pressure.FromPascals(force.Newtons / area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static ForcePerLength operator /(Force force, Length length) { return ForcePerLength.FromNewtonsPerMeter(force.Newtons / length.Meters); diff --git a/UnitsNet/CustomCode/Quantities/ForcePerLength.extra.cs b/UnitsNet/CustomCode/Quantities/ForcePerLength.extra.cs index bb9e870230..813190866f 100644 --- a/UnitsNet/CustomCode/Quantities/ForcePerLength.extra.cs +++ b/UnitsNet/CustomCode/Quantities/ForcePerLength.extra.cs @@ -5,19 +5,19 @@ namespace UnitsNet { public partial struct ForcePerLength { - /// Get from divided by . + /// Get from divided by . public static Force operator *(ForcePerLength forcePerLength, Length length) { return Force.FromNewtons(forcePerLength.NewtonsPerMeter * length.Meters); } - /// Get from divided by . + /// Get from divided by . public static Length operator /(Force force, ForcePerLength forcePerLength) { return Length.FromMeters(force.Newtons / forcePerLength.NewtonsPerMeter); } - /// Get from divided by . + /// Get from divided by . public static Pressure operator /(ForcePerLength forcePerLength, Length length) { return Pressure.FromNewtonsPerSquareMeter(forcePerLength.NewtonsPerMeter / length.Meters); diff --git a/UnitsNet/CustomCode/Quantities/HeatFlux.extra.cs b/UnitsNet/CustomCode/Quantities/HeatFlux.extra.cs index 940d38dcce..395661fb1f 100644 --- a/UnitsNet/CustomCode/Quantities/HeatFlux.extra.cs +++ b/UnitsNet/CustomCode/Quantities/HeatFlux.extra.cs @@ -5,7 +5,7 @@ namespace UnitsNet { public partial struct HeatFlux { - /// Get from times . + /// Get from times . public static Power operator *(HeatFlux heatFlux, Area area) { return Power.FromWatts(heatFlux.WattsPerSquareMeter * area.SquareMeters); diff --git a/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs b/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs index 56677fb252..f43b75534c 100644 --- a/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/KinematicViscosity.extra.cs @@ -7,37 +7,37 @@ namespace UnitsNet { public partial struct KinematicViscosity { - /// Get from divided by . + /// Get from divided by . public static Speed operator /(KinematicViscosity kinematicViscosity, Length length) { return Speed.FromMetersPerSecond(kinematicViscosity.SquareMetersPerSecond / length.Meters); } - /// Get from times . + /// Get from times . public static Area operator *(KinematicViscosity kinematicViscosity, TimeSpan timeSpan) { return Area.FromSquareMeters(kinematicViscosity.SquareMetersPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Area operator *(TimeSpan timeSpan, KinematicViscosity kinematicViscosity) { return Area.FromSquareMeters(kinematicViscosity.SquareMetersPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Area operator *(KinematicViscosity kinematicViscosity, Duration duration) { return Area.FromSquareMeters(kinematicViscosity.SquareMetersPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static Area operator *(Duration duration, KinematicViscosity kinematicViscosity) { return Area.FromSquareMeters(kinematicViscosity.SquareMetersPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static DynamicViscosity operator *(KinematicViscosity kinematicViscosity, Density density) { return DynamicViscosity.FromNewtonSecondsPerMeterSquared(kinematicViscosity.SquareMetersPerSecond * density.KilogramsPerCubicMeter); diff --git a/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs b/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs index 8d15572028..6f675602e0 100644 --- a/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs +++ b/UnitsNet/CustomCode/Quantities/LapseRate.extra.cs @@ -5,16 +5,16 @@ namespace UnitsNet { public partial struct LapseRate { - /// Get from divided by . + /// Get from divided by . public static Length operator /(TemperatureDelta left, LapseRate right) { return Length.FromKilometers(left.Kelvins / right.DegreesCelciusPerKilometer); } - /// Get from times . + /// Get from times . public static TemperatureDelta operator *(Length left, LapseRate right) => right * left; - /// Get from times . + /// Get from times . public static TemperatureDelta operator *(LapseRate left, Length right) { return TemperatureDelta.FromDegreesCelsius(left.DegreesCelciusPerKilometer * right.Kilometers); diff --git a/UnitsNet/CustomCode/Quantities/Length.extra.cs b/UnitsNet/CustomCode/Quantities/Length.extra.cs index fe240f8ea7..97f64c4805 100644 --- a/UnitsNet/CustomCode/Quantities/Length.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Length.extra.cs @@ -34,26 +34,23 @@ public FeetInches FeetInches /// public static Length FromFeetInches(double feet, double inches) { - return FromInches(InchesInOneFoot * feet + inches); + return FromInches(InchesInOneFoot*feet + inches); } /// - /// Special parsing of feet/inches strings, commonly used. - /// 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″, 2′4″, 2 ft 4 in. - /// The apostrophe can be ′ and '. - /// The double prime can be ″ and ". - /// https://en.wikipedia.org/wiki/Foot_(unit) + /// Special parsing of feet/inches strings, commonly used. + /// 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″, 2′4″, 2 ft 4 in. + /// The apostrophe can be ′ and '. + /// The double prime can be ″ and ". + /// https://en.wikipedia.org/wiki/Foot_(unit) /// /// - /// - /// Optionally specify the culture format numbers and localize unit abbreviations. Defaults to - /// thread's culture. - /// + /// Optionally specify the culture format numbers and localize unit abbreviations. Defaults to thread's culture. /// Parsed length. public static Length ParseFeetInches([NotNull] string str, IFormatProvider formatProvider = null) { if (str == null) throw new ArgumentNullException(nameof(str)); - if (!TryParseFeetInches(str, out var result, formatProvider)) + if (!TryParseFeetInches(str, out Length result, formatProvider)) { // A bit lazy, but I didn't want to duplicate this edge case implementation just to get more narrow exception descriptions. throw new FormatException("Unable to parse feet and inches. Expected format \"2' 4\"\" or \"2 ft 4 in\". Whitespace is optional."); @@ -63,18 +60,15 @@ public static Length ParseFeetInches([NotNull] string str, IFormatProvider forma } /// - /// Special parsing of feet/inches strings, commonly used. - /// 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″, 2′4″, 2 ft 4 in. - /// The apostrophe can be ′ and '. - /// The double prime can be ″ and ". - /// https://en.wikipedia.org/wiki/Foot_(unit) + /// Special parsing of feet/inches strings, commonly used. + /// 2 feet 4 inches is sometimes denoted as 2′−4″, 2′ 4″, 2′4″, 2 ft 4 in. + /// The apostrophe can be ′ and '. + /// The double prime can be ″ and ". + /// https://en.wikipedia.org/wiki/Foot_(unit) /// /// /// Parsed length. - /// - /// Optionally specify the culture format numbers and localize unit abbreviations. Defaults to - /// thread's culture. - /// + /// Optionally specify the culture format numbers and localize unit abbreviations. Defaults to thread's culture. public static bool TryParseFeetInches([CanBeNull] string str, out Length result, IFormatProvider formatProvider = null) { if (str == null) @@ -87,36 +81,30 @@ public static bool TryParseFeetInches([CanBeNull] string str, out Length result, // This succeeds if only feet or inches are given, not both if (TryParse(str, formatProvider, out result)) - { return true; - } var quantityParser = QuantityParser.Default; - var footRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Foot, formatProvider, false); - var inchRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Inch, formatProvider, false); + string footRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Foot, formatProvider, matchEntireString: false); + string inchRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Inch, formatProvider, matchEntireString: false); // Match entire string exactly - var pattern = $@"^(?\-?)(?{footRegex})\s?(?{inchRegex})$"; + string pattern = $@"^(?\-?)(?{footRegex})\s?(?{inchRegex})$"; var match = new Regex(pattern, RegexOptions.Singleline).Match(str); if (!match.Success) - { return false; - } var negativeSignGroup = match.Groups["negativeSign"]; var feetGroup = match.Groups["feet"]; var inchesGroup = match.Groups["inches"]; - if (TryParse(feetGroup.Value, formatProvider, out var feet) && - TryParse(inchesGroup.Value, formatProvider, out var inches)) + if (TryParse(feetGroup.Value, formatProvider, out Length feet) && + TryParse(inchesGroup.Value, formatProvider, out Length inches)) { result = feet + inches; - if (negativeSignGroup.Length > 0) - { + if(negativeSignGroup.Length > 0) result = -result; - } return true; } @@ -125,61 +113,61 @@ public static bool TryParseFeetInches([CanBeNull] string str, out Length result, return false; } - /// Get from divided by . + /// Get from divided by . public static Speed operator /(Length length, TimeSpan timeSpan) { - return Speed.FromMetersPerSecond(length.Meters / timeSpan.TotalSeconds); + return Speed.FromMetersPerSecond(length.Meters/timeSpan.TotalSeconds); } - /// Get from divided by . + /// Get from divided by . public static Speed operator /(Length length, Duration duration) { - return Speed.FromMetersPerSecond(length.Meters / duration.Seconds); + return Speed.FromMetersPerSecond(length.Meters/duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static Duration operator /(Length length, Speed speed) { - return Duration.FromSeconds(length.Meters / speed.MetersPerSecond); + return Duration.FromSeconds(length.Meters/speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static Area operator *(Length length1, Length length2) { - return Area.FromSquareMeters(length1.Meters * length2.Meters); + return Area.FromSquareMeters(length1.Meters*length2.Meters); } - /// Get from times . + /// Get from times . public static Volume operator *(Area area, Length length) { - return Volume.FromCubicMeters(area.SquareMeters * length.Meters); + return Volume.FromCubicMeters(area.SquareMeters*length.Meters); } - /// Get from times . + /// Get from times . public static Volume operator *(Length length, Area area) { - return Volume.FromCubicMeters(area.SquareMeters * length.Meters); + return Volume.FromCubicMeters(area.SquareMeters*length.Meters); } - /// Get from times . + /// Get from times . public static Torque operator *(Force force, Length length) { - return Torque.FromNewtonMeters(force.Newtons * length.Meters); + return Torque.FromNewtonMeters(force.Newtons*length.Meters); } - /// Get from times . + /// Get from times . public static Torque operator *(Length length, Force force) { - return Torque.FromNewtonMeters(force.Newtons * length.Meters); + return Torque.FromNewtonMeters(force.Newtons*length.Meters); } - /// Get from times . + /// Get from times . public static KinematicViscosity operator *(Length length, Speed speed) { - return KinematicViscosity.FromSquareMetersPerSecond(length.Meters * speed.MetersPerSecond); + return KinematicViscosity.FromSquareMetersPerSecond(length.Meters*speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static Pressure operator *(Length length, SpecificWeight specificWeight) { return new Pressure(length.Meters * specificWeight.NewtonsPerCubicMeter, PressureUnit.Pascal); @@ -187,8 +175,8 @@ public static bool TryParseFeetInches([CanBeNull] string str, out Length result, } /// - /// Representation of feet and inches, used to preserve the original values when constructing by - /// and later output them unaltered with . + /// Representation of feet and inches, used to preserve the original values when constructing by + /// and later output them unaltered with . /// public sealed class FeetInches { @@ -211,7 +199,7 @@ public FeetInches(double feet, double inches) /// public double Inches { get; } - /// + /// public override string ToString() { return ToString(null); @@ -223,7 +211,7 @@ public override string ToString() /// Length.FromFeetInches(3,2).FeetInches.ToString() outputs: "3 ft 2 in" /// /// Optional culture to format number and localize unit abbreviations. - /// If null, defaults to . + /// If null, defaults to . /// public string ToString([CanBeNull] IFormatProvider cultureInfo) { diff --git a/UnitsNet/CustomCode/Quantities/Level.extra.cs b/UnitsNet/CustomCode/Quantities/Level.extra.cs index 29645ffe79..a7b1a82825 100644 --- a/UnitsNet/CustomCode/Quantities/Level.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Level.extra.cs @@ -17,22 +17,17 @@ public partial struct Level public Level(double quantity, double reference) : this() { - var errorMessage = + string errorMessage = $"The base-10 logarithm of a number ≤ 0 is undefined ({quantity}/{reference})."; // ReSharper disable CompareOfFloatsByEqualityOperator if (quantity == 0 || quantity < 0 && reference > 0) - { throw new ArgumentOutOfRangeException(nameof(quantity), errorMessage); - } - if (reference == 0 || quantity > 0 && reference < 0) - { throw new ArgumentOutOfRangeException(nameof(reference), errorMessage); - } // ReSharper restore CompareOfFloatsByEqualityOperator - _value = 10 * Math.Log10(quantity / reference); + _value = 10*Math.Log10(quantity/reference); _unit = LevelUnit.Decibel; } } diff --git a/UnitsNet/CustomCode/Quantities/Mass.extra.cs b/UnitsNet/CustomCode/Quantities/Mass.extra.cs index 436f0e5cab..418adf58f8 100644 --- a/UnitsNet/CustomCode/Quantities/Mass.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Mass.extra.cs @@ -2,8 +2,8 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using System.Globalization; using System.Threading; +using System.Globalization; using JetBrains.Annotations; using UnitsNet.Units; @@ -11,7 +11,7 @@ namespace UnitsNet { public partial struct Mass { - /// Get from of gravity. + /// Get from of gravity. public static Mass FromGravitationalForce(Force f) { return new Mass(f.KilogramsForce, MassUnit.Kilogram); @@ -44,28 +44,28 @@ public StonePounds StonePounds /// public static Mass FromStonePounds(double stone, double pounds) { - return FromPounds(StonesInOnePound * stone + pounds); + return FromPounds(StonesInOnePound*stone + pounds); } - /// Get from divided by . + /// Get from divided by . public static MassFlow operator /(Mass mass, TimeSpan timeSpan) { - return MassFlow.FromKilogramsPerSecond(mass.Kilograms / timeSpan.TotalSeconds); + return MassFlow.FromKilogramsPerSecond(mass.Kilograms/timeSpan.TotalSeconds); } - /// Get from divided by . + /// Get from divided by . public static MassFlow operator /(Mass mass, Duration duration) { - return MassFlow.FromKilogramsPerSecond(mass.Kilograms / duration.Seconds); + return MassFlow.FromKilogramsPerSecond(mass.Kilograms/duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static Density operator /(Mass mass, Volume volume) { - return Density.FromKilogramsPerCubicMeter(mass.Kilograms / volume.CubicMeters); + return Density.FromKilogramsPerCubicMeter(mass.Kilograms/volume.CubicMeters); } - /// Get from divided by . + /// Get from divided by . public static Volume operator /(Mass mass, Density density) { return Volume.FromCubicMeters(mass.Kilograms / density.KilogramsPerCubicMeter); @@ -77,22 +77,22 @@ public static Mass FromStonePounds(double stone, double pounds) return AmountOfSubstance.FromMoles(mass.Kilograms / molarMass.KilogramsPerMole); } - /// Get from times . + /// Get from times . public static Force operator *(Mass mass, Acceleration acceleration) { - return Force.FromNewtons(mass.Kilograms * acceleration.MetersPerSecondSquared); + return Force.FromNewtons(mass.Kilograms*acceleration.MetersPerSecondSquared); } - /// Get from times . + /// Get from times . public static Force operator *(Acceleration acceleration, Mass mass) { - return Force.FromNewtons(mass.Kilograms * acceleration.MetersPerSecondSquared); + return Force.FromNewtons(mass.Kilograms*acceleration.MetersPerSecondSquared); } } /// - /// Representation of stone and pounds, used to preserve the original values when constructing by - /// and later output them unaltered with . + /// Representation of stone and pounds, used to preserve the original values when constructing by + /// and later output them unaltered with . /// public sealed class StonePounds { @@ -115,7 +115,7 @@ public StonePounds(double stone, double pounds) /// public double Pounds { get; } - /// + /// public override string ToString() { return ToString(null); @@ -127,7 +127,7 @@ public override string ToString() /// Mass.FromStonePounds(3,2).StonePounds.ToString() outputs: "3 st 2 lb" /// /// Optional culture to format number and localize unit abbreviations. - /// If null, defaults to . + /// If null, defaults to . /// public string ToString([CanBeNull] IFormatProvider cultureInfo) { diff --git a/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs b/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs index c063162ec9..edce6c4ee2 100644 --- a/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassConcentration.extra.cs @@ -1,13 +1,14 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using UnitsNet.Units; + namespace UnitsNet { public partial struct MassConcentration { /// - /// Get from this using the known component - /// . + /// Get from this using the known component . /// /// public Molarity ToMolarity(MolarMass molecularWeight) @@ -16,8 +17,7 @@ public Molarity ToMolarity(MolarMass molecularWeight) } /// - /// Get from this using the known component - /// . + /// Get from this using the known component . /// /// /// @@ -48,7 +48,7 @@ public static MassConcentration FromVolumeConcentration(VolumeConcentration volu #endregion #region Operators - + /// Get from times . public static Mass operator *(MassConcentration density, Volume volume) { @@ -60,25 +60,20 @@ public static MassConcentration FromVolumeConcentration(VolumeConcentration volu { return Mass.FromKilograms(density.KilogramsPerCubicMeter * volume.CubicMeters); } - - /// - /// Get from divided by the component's - /// . - /// + + /// Get from divided by the component's . public static Molarity operator /(MassConcentration massConcentration, MolarMass componentMass) { return Molarity.FromMolesPerCubicMeter(massConcentration.GramsPerCubicMeter / componentMass.GramsPerMole); } - /// - /// Get from divided by the component's - /// . - /// + /// Get from divided by the component's . public static VolumeConcentration operator /(MassConcentration massConcentration, Density componentDensity) { return VolumeConcentration.FromDecimalFractions(massConcentration.KilogramsPerCubicMeter / componentDensity.KilogramsPerCubicMeter); } #endregion + } } diff --git a/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs b/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs index aa1233fd72..e60c5c75d8 100644 --- a/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassFlow.extra.cs @@ -7,67 +7,67 @@ namespace UnitsNet { public partial struct MassFlow { - /// Get from times . + /// Get from times . public static Mass operator *(MassFlow massFlow, TimeSpan time) { return Mass.FromKilograms(massFlow.KilogramsPerSecond * time.TotalSeconds); } - /// Get from times . + /// Get from times . public static Mass operator *(TimeSpan time, MassFlow massFlow) { return Mass.FromKilograms(massFlow.KilogramsPerSecond * time.TotalSeconds); } - /// Get from times . + /// Get from times . public static Mass operator *(MassFlow massFlow, Duration duration) { return Mass.FromKilograms(massFlow.KilogramsPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static Mass operator *(Duration duration, MassFlow massFlow) { return Mass.FromKilograms(massFlow.KilogramsPerSecond * duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static Power operator /(MassFlow massFlow, BrakeSpecificFuelConsumption bsfc) { return Power.FromWatts(massFlow.KilogramsPerSecond / bsfc.KilogramsPerJoule); } - /// Get from divided by . + /// Get from divided by . public static BrakeSpecificFuelConsumption operator /(MassFlow massFlow, Power power) { return BrakeSpecificFuelConsumption.FromKilogramsPerJoule(massFlow.KilogramsPerSecond / power.Watts); } - /// Get from times . + /// Get from times . public static Power operator *(MassFlow massFlow, SpecificEnergy specificEnergy) { return Power.FromWatts(massFlow.KilogramsPerSecond * specificEnergy.JoulesPerKilogram); } - /// Get from divided by . + /// Get from divided by . public static MassFlux operator /(MassFlow massFlow, Area area) { return MassFlux.FromKilogramsPerSecondPerSquareMeter(massFlow.KilogramsPerSecond / area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static Area operator /(MassFlow massFlow, MassFlux massFlux) { return Area.FromSquareMeters(massFlow.KilogramsPerSecond / massFlux.KilogramsPerSecondPerSquareMeter); } - /// Get from divided by . + /// Get from divided by . public static Density operator /(MassFlow massFlow, VolumeFlow volumeFlow) { return Density.FromKilogramsPerCubicMeter(massFlow.KilogramsPerSecond / volumeFlow.CubicMetersPerSecond); } - /// Get from divided by . + /// Get from divided by . public static VolumeFlow operator /(MassFlow massFlow, Density density) { return VolumeFlow.FromCubicMetersPerSecond(massFlow.KilogramsPerSecond / density.KilogramsPerCubicMeter); diff --git a/UnitsNet/CustomCode/Quantities/MassFlux.extra.cs b/UnitsNet/CustomCode/Quantities/MassFlux.extra.cs index 9ec650f5cd..654ce48a20 100644 --- a/UnitsNet/CustomCode/Quantities/MassFlux.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassFlux.extra.cs @@ -5,19 +5,19 @@ namespace UnitsNet { public partial struct MassFlux { - /// Get from divided by . + /// Get from divided by . public static Density operator /(MassFlux massFlux, Speed speed) { return Density.FromKilogramsPerCubicMeter(massFlux.KilogramsPerSecondPerSquareMeter / speed.MetersPerSecond); } - /// Get from divided by . + /// Get from divided by . public static Speed operator /(MassFlux massFlux, Density density) { return Speed.FromMetersPerSecond(massFlux.KilogramsPerSecondPerSquareMeter / density.KilogramsPerCubicMeter); } - /// Get from times . + /// Get from times . public static MassFlow operator *(MassFlux massFlux, Area area) { return MassFlow.FromGramsPerSecond(massFlux.GramsPerSecondPerSquareMeter * area.SquareMeters); diff --git a/UnitsNet/CustomCode/Quantities/MassFraction.extra.cs b/UnitsNet/CustomCode/Quantities/MassFraction.extra.cs index 069d6ffb2b..c685887214 100644 --- a/UnitsNet/CustomCode/Quantities/MassFraction.extra.cs +++ b/UnitsNet/CustomCode/Quantities/MassFraction.extra.cs @@ -1,15 +1,11 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using UnitsNet.Units; +using UnitsNet.Units; namespace UnitsNet { public partial struct MassFraction { /// - /// Get the of the component by multiplying the of the mixture and this - /// . + /// Get the of the component by multiplying the of the mixture and this . /// /// The total mass of the mixture /// The actual mass of the component involved in this mixture @@ -19,8 +15,7 @@ public Mass GetComponentMass(Mass totalMass) } /// - /// Get the total of the mixture by dividing the of the component by this - /// + /// Get the total of the mixture by dividing the of the component by this /// /// The actual mass of the component involved in this mixture /// The total mass of the mixture @@ -41,25 +36,22 @@ public static MassFraction FromMasses(Mass componentMass, Mass mixtureMass) #endregion - /// Get from multiplied by a . + /// Get from multiplied by a . public static Mass operator *(MassFraction massFraction, Mass mass) { return Mass.FromKilograms(massFraction.DecimalFractions * mass.Kilograms); } - /// Get from multiplied by a . + /// Get from multiplied by a . public static Mass operator *(Mass mass, MassFraction massFraction) { return Mass.FromKilograms(massFraction.DecimalFractions * mass.Kilograms); } - - /// - /// Get the total by dividing the component by a - /// . - /// + /// Get the total by dividing the component by a . public static Mass operator /(Mass mass, MassFraction massFraction) { return Mass.FromKilograms(mass.Kilograms / massFraction.DecimalFractions); } + } } diff --git a/UnitsNet/CustomCode/Quantities/Molarity.extra.cs b/UnitsNet/CustomCode/Quantities/Molarity.extra.cs index a64e743dac..53af6eeb15 100644 --- a/UnitsNet/CustomCode/Quantities/Molarity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Molarity.extra.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; using UnitsNet.Units; namespace UnitsNet @@ -9,9 +6,9 @@ namespace UnitsNet public partial struct Molarity { /// - /// Construct from divided by . + /// Construct from divided by . /// - /// + /// [Obsolete("This constructor will be removed in favor of operator overload MassConcentration.op_Division(MassConcentration,MolarMass).")] public Molarity(Density density, Mass molecularWeight) : this() @@ -21,10 +18,10 @@ public Molarity(Density density, Mass molecularWeight) } /// - /// Get a from this . + /// Get a from this . /// /// - /// + /// [Obsolete("This method will be removed in favor of ToMassConcentration(MolarMass)")] public Density ToDensity(Mass molecularWeight) { @@ -32,16 +29,16 @@ public Density ToDensity(Mass molecularWeight) } /// - /// Get a from this . + /// Get a from this . /// /// - public MassConcentration ToMassConcentration(MolarMass molecularWeight) + public MassConcentration ToMassConcentration(MolarMass molecularWeight) { - return this * molecularWeight; + return this * molecularWeight; } /// - /// Get a from this . + /// Get a from this . /// /// /// @@ -53,7 +50,7 @@ public VolumeConcentration ToVolumeConcentration(Density componentDensity, Molar #region Static Methods /// - /// Get from . + /// Get from . /// /// /// @@ -64,8 +61,7 @@ public static Molarity FromDensity(Density density, Mass molecularWeight) } /// - /// Get from and known component and - /// . + /// Get from and known component and . /// /// /// @@ -92,24 +88,19 @@ public static Molarity FromVolumeConcentration(VolumeConcentration volumeConcent return MassConcentration.FromGramsPerCubicMeter(molarity.MolesPerCubicMeter * componentMass.GramsPerMole); } - /// - /// Get from diluting the current by the given - /// . - /// + /// Get from diluting the current by the given . public static Molarity operator *(Molarity molarity, VolumeConcentration volumeConcentration) { return new Molarity(molarity.MolesPerCubicMeter * volumeConcentration.DecimalFractions, MolarityUnit.MolesPerCubicMeter); } - /// - /// Get from diluting the current by the given - /// . - /// + /// Get from diluting the current by the given . public static Molarity operator *(VolumeConcentration volumeConcentration, Molarity molarity) { return new Molarity(molarity.MolesPerCubicMeter * volumeConcentration.DecimalFractions, MolarityUnit.MolesPerCubicMeter); } #endregion + } } diff --git a/UnitsNet/CustomCode/Quantities/Power.extra.cs b/UnitsNet/CustomCode/Quantities/Power.extra.cs index 426e54a4dd..4b61a19b76 100644 --- a/UnitsNet/CustomCode/Quantities/Power.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Power.extra.cs @@ -21,76 +21,76 @@ public PowerRatio ToPowerRatio() return PowerRatio.FromPower(this); } - /// Get from times . + /// Get from times . public static Energy operator *(Power power, TimeSpan time) { return Energy.FromJoules(power.Watts * time.TotalSeconds); } - /// Get from times . + /// Get from times . public static Energy operator *(TimeSpan time, Power power) { return Energy.FromJoules(power.Watts * time.TotalSeconds); } - /// Get from times . + /// Get from times . public static Energy operator *(Power power, Duration duration) { return Energy.FromJoules(power.Watts * duration.Seconds); } - /// Get from times . + /// Get from times . public static Energy operator *(Duration duration, Power power) { return Energy.FromJoules(power.Watts * duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static Force operator /(Power power, Speed speed) { return Force.FromNewtons(power.Watts / speed.MetersPerSecond); } - /// Get from divided by . + /// Get from divided by . public static Torque operator /(Power power, RotationalSpeed rotationalSpeed) { return Torque.FromNewtonMeters(power.Watts / rotationalSpeed.RadiansPerSecond); } - /// Get from divided by . + /// Get from divided by . public static RotationalSpeed operator /(Power power, Torque torque) { return RotationalSpeed.FromRadiansPerSecond(power.Watts / torque.NewtonMeters); } - /// Get from times . + /// Get from times . public static MassFlow operator *(Power power, BrakeSpecificFuelConsumption bsfc) { return MassFlow.FromKilogramsPerSecond(bsfc.KilogramsPerJoule * power.Watts); } - /// Get from divided by . + /// Get from divided by . public static SpecificEnergy operator /(Power power, MassFlow massFlow) { return SpecificEnergy.FromJoulesPerKilogram(power.Watts / massFlow.KilogramsPerSecond); } - /// Get from divided by . + /// Get from divided by . public static MassFlow operator /(Power power, SpecificEnergy specificEnergy) { return MassFlow.FromKilogramsPerSecond(power.Watts / specificEnergy.JoulesPerKilogram); } - /// Get from divided by . + /// Get from divided by . public static HeatFlux operator /(Power power, Area area) { return HeatFlux.FromWattsPerSquareMeter(power.Watts / area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static Area operator /(Power power, HeatFlux heatFlux) { - return Area.FromSquareMeters(power.Watts / heatFlux.WattsPerSquareMeter); + return Area.FromSquareMeters( power.Watts / heatFlux.WattsPerSquareMeter ); } } } diff --git a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs index e9866b5d24..f563f720ae 100644 --- a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs @@ -12,14 +12,13 @@ public partial struct PowerRatio /// Initializes a new instance of the struct from the specified power referenced to one watt. /// /// The power relative to one watt. + public PowerRatio(Power power) : this() { if (power.Watts <= 0) - { throw new ArgumentOutOfRangeException( nameof(power), "The base-10 logarithm of a number ≤ 0 is undefined. Power must be greater than 0 W."); - } // P(dBW) = 10*log10(value(W)/reference(W)) _value = 10 * Math.Log10(power.Watts / 1); diff --git a/UnitsNet/CustomCode/Quantities/Pressure.extra.cs b/UnitsNet/CustomCode/Quantities/Pressure.extra.cs index fa5a83aa16..ecaf977ed6 100644 --- a/UnitsNet/CustomCode/Quantities/Pressure.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Pressure.extra.cs @@ -1,34 +1,32 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using UnitsNet.Units; - namespace UnitsNet { public partial struct Pressure { - /// Get from times . + /// Get from times . public static Force operator *(Pressure pressure, Area area) { return Force.FromNewtons(pressure.Pascals * area.SquareMeters); } - /// Get from times . + /// Get from times . public static Force operator *(Area area, Pressure pressure) { return Force.FromNewtons(pressure.Pascals * area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static Length operator /(Pressure pressure, SpecificWeight specificWeight) { - return new Length(pressure.Pascals / specificWeight.NewtonsPerCubicMeter, LengthUnit.Meter); + return new Length(pressure.Pascals / specificWeight.NewtonsPerCubicMeter, UnitsNet.Units.LengthUnit.Meter); } - /// Get from divided by . + /// Get from divided by . public static SpecificWeight operator /(Pressure pressure, Length length) { - return new SpecificWeight(pressure.Pascals / length.Meters, SpecificWeightUnit.NewtonPerCubicMeter); + return new SpecificWeight(pressure.Pascals / length.Meters, UnitsNet.Units.SpecificWeightUnit.NewtonPerCubicMeter); } } } diff --git a/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs b/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs index 411d8ff43e..a1f18c79cd 100644 --- a/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs +++ b/UnitsNet/CustomCode/Quantities/RotationalSpeed.extra.cs @@ -7,25 +7,25 @@ namespace UnitsNet { public partial struct RotationalSpeed { - /// Get from times . + /// Get from times . public static Angle operator *(RotationalSpeed rotationalSpeed, TimeSpan timeSpan) { return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Angle operator *(TimeSpan timeSpan, RotationalSpeed rotationalSpeed) { return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Angle operator *(RotationalSpeed rotationalSpeed, Duration duration) { return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static Angle operator *(Duration duration, RotationalSpeed rotationalSpeed) { return Angle.FromRadians(rotationalSpeed.RadiansPerSecond * duration.Seconds); diff --git a/UnitsNet/CustomCode/Quantities/RotationalStiffness.extra.cs b/UnitsNet/CustomCode/Quantities/RotationalStiffness.extra.cs index ea7afb93be..48b9342455 100644 --- a/UnitsNet/CustomCode/Quantities/RotationalStiffness.extra.cs +++ b/UnitsNet/CustomCode/Quantities/RotationalStiffness.extra.cs @@ -5,25 +5,19 @@ namespace UnitsNet { public partial struct RotationalStiffness { - /// Get from times . + /// Get from times . public static Torque operator *(RotationalStiffness rotationalStiffness, Angle angle) { return Torque.FromNewtonMeters(rotationalStiffness.NewtonMetersPerRadian * angle.Radians); } - /// - /// Get from divided by - /// . - /// + /// Get from divided by . public static RotationalStiffnessPerLength operator /(RotationalStiffness rotationalStiffness, Length length) { return RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(rotationalStiffness.NewtonMetersPerRadian / length.Meters); } - /// - /// Get from divided by - /// . - /// + /// Get from divided by . public static Length operator /(RotationalStiffness rotationalStiffness, RotationalStiffnessPerLength rotationalStiffnessPerLength) { return Length.FromMeters(rotationalStiffness.NewtonMetersPerRadian / rotationalStiffnessPerLength.NewtonMetersPerRadianPerMeter); diff --git a/UnitsNet/CustomCode/Quantities/RotationalStiffnessPerLength.extra.cs b/UnitsNet/CustomCode/Quantities/RotationalStiffnessPerLength.extra.cs index 33ad3bbd53..1aef772c05 100644 --- a/UnitsNet/CustomCode/Quantities/RotationalStiffnessPerLength.extra.cs +++ b/UnitsNet/CustomCode/Quantities/RotationalStiffnessPerLength.extra.cs @@ -2,15 +2,11 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. // ReSharper disable once CheckNamespace - namespace UnitsNet { public partial struct RotationalStiffnessPerLength { - /// - /// Get from times - /// . - /// + /// Get from times . public static RotationalStiffness operator *(RotationalStiffnessPerLength rotationalStiffness, Length length) { return RotationalStiffness.FromNewtonMetersPerRadian(rotationalStiffness.NewtonMetersPerRadianPerMeter * length.Meters); diff --git a/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs b/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs index c8d3dcfcaa..45f4473f80 100644 --- a/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs +++ b/UnitsNet/CustomCode/Quantities/SpecificEnergy.extra.cs @@ -5,37 +5,31 @@ namespace UnitsNet { public partial struct SpecificEnergy { - /// Get from times . + /// Get from times . public static Energy operator *(SpecificEnergy specificEnergy, Mass mass) { return Energy.FromJoules(specificEnergy.JoulesPerKilogram * mass.Kilograms); } - /// Get from times . + /// Get from times . public static Energy operator *(Mass mass, SpecificEnergy specificEnergy) { return Energy.FromJoules(specificEnergy.JoulesPerKilogram * mass.Kilograms); } - /// - /// Get from divided by - /// . - /// + /// Get from divided by . public static BrakeSpecificFuelConsumption operator /(double value, SpecificEnergy specificEnergy) { return BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value / specificEnergy.JoulesPerKilogram); } - /// - /// Get from times - /// . - /// + /// Get from times . public static double operator *(SpecificEnergy specificEnergy, BrakeSpecificFuelConsumption bsfc) { return specificEnergy.JoulesPerKilogram * bsfc.KilogramsPerJoule; } - /// Get from times . + /// Get from times . public static Power operator *(SpecificEnergy specificEnergy, MassFlow massFlow) { return Power.FromWatts(massFlow.KilogramsPerSecond * specificEnergy.JoulesPerKilogram); diff --git a/UnitsNet/CustomCode/Quantities/SpecificVolume.extra.cs b/UnitsNet/CustomCode/Quantities/SpecificVolume.extra.cs index 7b14c6dc1f..f284f8bb28 100644 --- a/UnitsNet/CustomCode/Quantities/SpecificVolume.extra.cs +++ b/UnitsNet/CustomCode/Quantities/SpecificVolume.extra.cs @@ -5,13 +5,13 @@ namespace UnitsNet { public partial struct SpecificVolume { - /// Get from divided by . + /// Get from divided by . public static Density operator /(double constant, SpecificVolume volume) { return Density.FromKilogramsPerCubicMeter(constant / volume.CubicMetersPerKilogram); } - /// Get from times . + /// Get from times . public static Volume operator *(SpecificVolume volume, Mass mass) { return Volume.FromCubicMeters(volume.CubicMetersPerKilogram * mass.Kilograms); diff --git a/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs b/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs index 66b6b0413d..85f4f8bae1 100644 --- a/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs +++ b/UnitsNet/CustomCode/Quantities/SpecificWeight.extra.cs @@ -7,34 +7,34 @@ namespace UnitsNet { public partial struct SpecificWeight { - /// Get from times . + /// Get from times . public static Pressure operator *(SpecificWeight specificWeight, Length length) { - return new Pressure(specificWeight.NewtonsPerCubicMeter * length.Meters, PressureUnit.Pascal); + return new Pressure(specificWeight.NewtonsPerCubicMeter * length.Meters, UnitsNet.Units.PressureUnit.Pascal); } - /// Get from times . + /// Get from times . public static ForcePerLength operator *(SpecificWeight specificWeight, Area area) { return new ForcePerLength(specificWeight.NewtonsPerCubicMeter * area.SquareMeters, ForcePerLengthUnit.NewtonPerMeter); } - /// Get from times . + /// Get from times . public static ForcePerLength operator *(Area area, SpecificWeight specificWeight) { return new ForcePerLength(area.SquareMeters * specificWeight.NewtonsPerCubicMeter, ForcePerLengthUnit.NewtonPerMeter); } - /// Get from divided by . + /// Get from divided by . public static Acceleration operator /(SpecificWeight specificWeight, Density density) { - return new Acceleration(specificWeight.NewtonsPerCubicMeter / density.KilogramsPerCubicMeter, AccelerationUnit.MeterPerSecondSquared); + return new Acceleration(specificWeight.NewtonsPerCubicMeter / density.KilogramsPerCubicMeter, UnitsNet.Units.AccelerationUnit.MeterPerSecondSquared); } - /// Get from divided by . + /// Get from divided by . public static Density operator /(SpecificWeight specific, Acceleration acceleration) { - return new Density(specific.NewtonsPerCubicMeter / acceleration.MetersPerSecondSquared, DensityUnit.KilogramPerCubicMeter); + return new Density(specific.NewtonsPerCubicMeter / acceleration.MetersPerSecondSquared, UnitsNet.Units.DensityUnit.KilogramPerCubicMeter); } } } diff --git a/UnitsNet/CustomCode/Quantities/Speed.extra.cs b/UnitsNet/CustomCode/Quantities/Speed.extra.cs index b4675b594b..549fff0bea 100644 --- a/UnitsNet/CustomCode/Quantities/Speed.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Speed.extra.cs @@ -7,61 +7,61 @@ namespace UnitsNet { public partial struct Speed { - /// Get from divided by . + /// Get from divided by . public static Acceleration operator /(Speed speed, TimeSpan timeSpan) { return Acceleration.FromMetersPerSecondSquared(speed.MetersPerSecond / timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Length operator *(Speed speed, TimeSpan timeSpan) { return Length.FromMeters(speed.MetersPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Length operator *(TimeSpan timeSpan, Speed speed) { return Length.FromMeters(speed.MetersPerSecond * timeSpan.TotalSeconds); } - /// Get from divided by . + /// Get from divided by . public static Acceleration operator /(Speed speed, Duration duration) { return Acceleration.FromMetersPerSecondSquared(speed.MetersPerSecond / duration.Seconds); } - /// Get from times . + /// Get from times . public static Length operator *(Speed speed, Duration duration) { return Length.FromMeters(speed.MetersPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static Length operator *(Duration duration, Speed speed) { return Length.FromMeters(speed.MetersPerSecond * duration.Seconds); } - /// Get from times . + /// Get from times . public static KinematicViscosity operator *(Speed speed, Length length) { return KinematicViscosity.FromSquareMetersPerSecond(length.Meters * speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static SpecificEnergy operator *(Speed left, Speed right) { return SpecificEnergy.FromJoulesPerKilogram(left.MetersPerSecond * right.MetersPerSecond); } - /// Get from times . + /// Get from times . public static MassFlux operator *(Speed speed, Density density) { return MassFlux.FromKilogramsPerSecondPerSquareMeter(speed.MetersPerSecond * density.KilogramsPerCubicMeter); } - /// Get from times . + /// Get from times . public static VolumeFlow operator *(Speed speed, Area area) { return VolumeFlow.FromCubicMetersPerSecond(speed.MetersPerSecond * area.SquareMeters); diff --git a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs index 93b7495e03..cfce09a948 100644 --- a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs @@ -60,7 +60,7 @@ public partial struct Temperature /// The resulting . public Temperature Multiply(double factor, TemperatureUnit unit) { - var resultInUnit = As(unit) * factor; + double resultInUnit = As(unit) * factor; return From(resultInUnit, unit); } @@ -78,7 +78,7 @@ public Temperature Multiply(double factor, TemperatureUnit unit) /// The resulting . public Temperature Divide(double divisor, TemperatureUnit unit) { - var resultInUnit = As(unit) / divisor; + double resultInUnit = As(unit) / divisor; return From(resultInUnit, unit); } } diff --git a/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs b/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs index b9df5787cd..b3b3878cbb 100644 --- a/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs +++ b/UnitsNet/CustomCode/Quantities/TemperatureDelta.extra.cs @@ -5,19 +5,19 @@ namespace UnitsNet { public partial struct TemperatureDelta { - /// Get from divided by . + /// Get from divided by . public static LapseRate operator /(TemperatureDelta left, Length right) { return LapseRate.FromDegreesCelciusPerKilometer(left.DegreesCelsius / right.Kilometers); } - /// Get from times . + /// Get from times . public static SpecificEnergy operator *(SpecificEntropy specificEntropy, TemperatureDelta temperatureDelta) { return SpecificEnergy.FromJoulesPerKilogram(specificEntropy.JoulesPerKilogramKelvin * temperatureDelta.Kelvins); } - /// Get from times . + /// Get from times . public static SpecificEnergy operator *(TemperatureDelta temperatureDelta, SpecificEntropy specificEntropy) { return specificEntropy * temperatureDelta; diff --git a/UnitsNet/CustomCode/Quantities/Torque.extra.cs b/UnitsNet/CustomCode/Quantities/Torque.extra.cs index e6f9d759fa..26bd4f551b 100644 --- a/UnitsNet/CustomCode/Quantities/Torque.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Torque.extra.cs @@ -5,25 +5,25 @@ namespace UnitsNet { public partial struct Torque { - /// Get from times . + /// Get from times . public static Force operator /(Torque torque, Length length) { return Force.FromNewtons(torque.NewtonMeters / length.Meters); } - /// Get from times . + /// Get from times . public static Length operator /(Torque torque, Force force) { return Length.FromMeters(torque.NewtonMeters / force.Newtons); } - /// Get from times . + /// Get from times . public static RotationalStiffness operator /(Torque torque, Angle angle) { return RotationalStiffness.FromNewtonMetersPerRadian(torque.NewtonMeters / angle.Radians); } - /// Get from times . + /// Get from times . public static Angle operator /(Torque torque, RotationalStiffness rotationalStiffness) { return Angle.FromRadians(torque.NewtonMeters / rotationalStiffness.NewtonMetersPerRadian); diff --git a/UnitsNet/CustomCode/Quantities/Volume.extra.cs b/UnitsNet/CustomCode/Quantities/Volume.extra.cs index 2d991530e9..aab43915a4 100644 --- a/UnitsNet/CustomCode/Quantities/Volume.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Volume.extra.cs @@ -7,31 +7,31 @@ namespace UnitsNet { public partial struct Volume { - /// Get from divided by . + /// Get from divided by . public static Area operator /(Volume volume, Length length) { return Area.FromSquareMeters(volume.CubicMeters / length.Meters); } - /// Get from divided by . + /// Get from divided by . public static Length operator /(Volume volume, Area area) { return Length.FromMeters(volume.CubicMeters / area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static VolumeFlow operator /(Volume volume, Duration duration) { return VolumeFlow.FromCubicMetersPerSecond(volume.CubicMeters / duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static VolumeFlow operator /(Volume volume, TimeSpan timeSpan) { return VolumeFlow.FromCubicMetersPerSecond(volume.CubicMeters / timeSpan.TotalSeconds); } - /// Get from divided by . + /// Get from divided by . public static TimeSpan operator /(Volume volume, VolumeFlow volumeFlow) { return TimeSpan.FromSeconds(volume.CubicMeters / volumeFlow.CubicMetersPerSecond); diff --git a/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs b/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs index dd81003100..e90942cfd1 100644 --- a/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/VolumeConcentration.extra.cs @@ -1,15 +1,11 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using UnitsNet.Units; +using UnitsNet.Units; namespace UnitsNet { public partial struct VolumeConcentration { /// - /// Get from this and component - /// . + /// Get from this and component . /// /// /// @@ -19,8 +15,7 @@ public MassConcentration ToMassConcentration(Density componentDensity) } /// - /// Get from this and component and - /// . + /// Get from this and component and . /// /// /// @@ -33,8 +28,7 @@ public Molarity ToMolarity(Density componentDensity, MolarMass compontMolarMass) #region Static Methods /// - /// Get from a component and total mixture - /// . + /// Get from a component and total mixture . /// public static VolumeConcentration FromVolumes(Volume componentVolume, Volume mixtureMass) { @@ -42,8 +36,7 @@ public static VolumeConcentration FromVolumes(Volume componentVolume, Volume mix } /// - /// Get a from and a component and - /// . + /// Get a from and a component and . /// /// /// @@ -53,28 +46,24 @@ public static VolumeConcentration FromMolarity(Molarity molarity, Density compon return molarity * componentMolarMass / componentDensity; } + #endregion #region Operators - /// - /// Get from times the component - /// . - /// + /// Get from times the component . public static MassConcentration operator *(VolumeConcentration volumeConcentration, Density componentDensity) { return MassConcentration.FromKilogramsPerCubicMeter(volumeConcentration.DecimalFractions * componentDensity.KilogramsPerCubicMeter); } - - /// - /// Get from times the component - /// . - /// + + /// Get from times the component . public static MassConcentration operator *(Density componentDensity, VolumeConcentration volumeConcentration) { return MassConcentration.FromKilogramsPerCubicMeter(volumeConcentration.DecimalFractions * componentDensity.KilogramsPerCubicMeter); } - + #endregion + } } diff --git a/UnitsNet/CustomCode/Quantities/VolumeFlow.extra.cs b/UnitsNet/CustomCode/Quantities/VolumeFlow.extra.cs index 90b8c36e85..51e71e8180 100644 --- a/UnitsNet/CustomCode/Quantities/VolumeFlow.extra.cs +++ b/UnitsNet/CustomCode/Quantities/VolumeFlow.extra.cs @@ -7,37 +7,37 @@ namespace UnitsNet { public partial struct VolumeFlow { - /// Get from times . + /// Get from times . public static Volume operator *(VolumeFlow volumeFlow, TimeSpan timeSpan) { return Volume.FromCubicMeters(volumeFlow.CubicMetersPerSecond * timeSpan.TotalSeconds); } - /// Get from times . + /// Get from times . public static Volume operator *(VolumeFlow volumeFlow, Duration duration) { return Volume.FromCubicMeters(volumeFlow.CubicMetersPerSecond * duration.Seconds); } - /// Get from divided by . + /// Get from divided by . public static Speed operator /(VolumeFlow volumeFlow, Area area) { return Speed.FromMetersPerSecond(volumeFlow.CubicMetersPerSecond / area.SquareMeters); } - /// Get from divided by . + /// Get from divided by . public static Area operator /(VolumeFlow volumeFlow, Speed speed) { return Area.FromSquareMeters(volumeFlow.CubicMetersPerSecond / speed.MetersPerSecond); } - /// Get from times . + /// Get from times . public static MassFlow operator *(VolumeFlow volumeFlow, Density density) { return MassFlow.FromKilogramsPerSecond(volumeFlow.CubicMetersPerSecond * density.KilogramsPerCubicMeter); } - /// Get from times . + /// Get from times . public static MassFlow operator *(Density density, VolumeFlow volumeFlow) { return MassFlow.FromKilogramsPerSecond(volumeFlow.CubicMetersPerSecond * density.KilogramsPerCubicMeter); diff --git a/UnitsNet/CustomCode/Quantity.cs b/UnitsNet/CustomCode/Quantity.cs index 9592405b90..74fe89d86d 100644 --- a/UnitsNet/CustomCode/Quantity.cs +++ b/UnitsNet/CustomCode/Quantity.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -27,18 +24,17 @@ static Quantity() } /// - /// All enum values of , such as and - /// . + /// All enum values of , such as and . /// public static QuantityType[] Types { get; } /// - /// All enum value names of , such as "Length" and "Mass". + /// All enum value names of , such as "Length" and "Mass". /// public static string[] Names { get; } /// - /// All quantity information objects, such as and . + /// All quantity information objects, such as and . /// public static QuantityInfo[] Infos => InfosLazy.Value; @@ -47,63 +43,53 @@ static Quantity() /// /// Numeric value. /// Unit enum value. - /// An object. + /// An object. /// Unit value is not a know unit enum type. public static IQuantity From(QuantityValue value, Enum unit) { - if (TryFrom(value, unit, out var quantity)) - { + if (TryFrom(value, unit, out IQuantity quantity)) return quantity; - } throw new ArgumentException( $"Unit value {unit} of type {unit.GetType()} is not a known unit enum type. Expected types like UnitsNet.Units.LengthUnit. Did you pass in a third-party enum type defined outside UnitsNet library?"); } - /// + /// public static bool TryFrom(double value, Enum unit, out IQuantity quantity) { // Implicit cast to QuantityValue would prevent TryFrom from being called, // so we need to explicitly check this here for double arguments. if (double.IsNaN(value) || double.IsInfinity(value)) { - quantity = default; + quantity = default(IQuantity); return false; } - return TryFrom((QuantityValue) value, unit, out quantity); + return TryFrom((QuantityValue)value, unit, out quantity); } - /// + /// public static IQuantity Parse(Type quantityType, string quantityString) => Parse(null, quantityType, quantityString); /// /// Dynamically parse a quantity string representation. /// - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// - /// Type of quantity, such as . - /// - /// Quantity string representation, such as "1.5 kg". Must be compatible with given quantity - /// type. - /// + /// The format provider to use for lookup. Defaults to if null. + /// Type of quantity, such as . + /// Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type. /// The parsed quantity. /// Type must be of type UnitsNet.IQuantity -or- Type is not a known quantity type. public static IQuantity Parse([CanBeNull] IFormatProvider formatProvider, Type quantityType, string quantityString) { if (!typeof(IQuantity).Wrap().IsAssignableFrom(quantityType)) - { throw new ArgumentException($"Type {quantityType} must be of type UnitsNet.IQuantity."); - } - if (TryParse(formatProvider, quantityType, quantityString, out var quantity)) return quantity; + if (TryParse(formatProvider, quantityType, quantityString, out IQuantity quantity)) return quantity; throw new ArgumentException($"Quantity string could not be parsed to quantity {quantityType}."); } - /// + /// public static bool TryParse(Type quantityType, string quantityString, out IQuantity quantity) => TryParse(null, quantityType, quantityString, out quantity); diff --git a/UnitsNet/CustomCode/QuantityParser.cs b/UnitsNet/CustomCode/QuantityParser.cs index 3aa09a2e4f..0f4a4028e4 100644 --- a/UnitsNet/CustomCode/QuantityParser.cs +++ b/UnitsNet/CustomCode/QuantityParser.cs @@ -12,6 +12,7 @@ // ReSharper disable once CheckNamespace namespace UnitsNet { + internal delegate TQuantity QuantityFromDelegate(QuantityValue value, TUnitType fromUnit) where TQuantity : IQuantity where TUnitType : Enum; @@ -19,17 +20,14 @@ internal delegate TQuantity QuantityFromDelegate(Qu internal class QuantityParser { /// - /// Allow integer, floating point or exponential number formats. + /// Allow integer, floating point or exponential number formats. /// private const NumberStyles ParseNumberStyles = NumberStyles.Number | NumberStyles.Float | NumberStyles.AllowExponent; private readonly UnitAbbreviationsCache _unitAbbreviationsCache; private readonly UnitParser _unitParser; - static QuantityParser() - { - Default = new QuantityParser(UnitAbbreviationsCache.Default); - } + public static QuantityParser Default { get; } public QuantityParser(UnitAbbreviationsCache unitAbbreviationsCache) { @@ -37,7 +35,10 @@ public QuantityParser(UnitAbbreviationsCache unitAbbreviationsCache) _unitParser = new UnitParser(_unitAbbreviationsCache); } - public static QuantityParser Default { get; } + static QuantityParser() + { + Default = new QuantityParser(UnitAbbreviationsCache.Default); + } [SuppressMessage("ReSharper", "UseStringInterpolation")] internal TQuantity Parse([NotNull] string str, @@ -54,16 +55,13 @@ internal TQuantity Parse([NotNull] string str, : NumberFormatInfo.CurrentInfo; if (numFormat == null) - { throw new InvalidOperationException($"No number format was found for the given format provider: {formatProvider}"); - } var regex = CreateRegexForQuantity(formatProvider); if (!ExtractValueAndUnit(regex, str, out var valueString, out var unitString)) { - var ex = new FormatException( - "Unable to parse quantity. Expected the form \"{value} {unit abbreviation}\", such as \"5.5 m\". The spacing is optional."); + var ex = new FormatException("Unable to parse quantity. Expected the form \"{value} {unit abbreviation}\", such as \"5.5 m\". The spacing is optional."); ex.Data["input"] = str; throw ex; } @@ -81,31 +79,26 @@ internal bool TryParse([NotNull] string str, { result = default; - if (string.IsNullOrWhiteSpace(str)) return false; + if(string.IsNullOrWhiteSpace(str)) return false; str = str.Trim(); var numFormat = formatProvider != null ? (NumberFormatInfo) formatProvider.GetFormat(typeof(NumberFormatInfo)) : NumberFormatInfo.CurrentInfo; - if (numFormat == null) - { + if(numFormat == null) return false; - } var regex = CreateRegexForQuantity(formatProvider); if (!ExtractValueAndUnit(regex, str, out var valueString, out var unitString)) - { return false; - } return TryParseWithRegex(valueString, unitString, fromDelegate, formatProvider, out result); } /// - /// Workaround for C# not allowing to pass on 'out' param from type Length to IQuantity, even though the are - /// compatible. + /// Workaround for C# not allowing to pass on 'out' param from type Length to IQuantity, even though the are compatible. /// [SuppressMessage("ReSharper", "UseStringInterpolation")] internal bool TryParse([NotNull] string str, @@ -178,14 +171,10 @@ private bool TryParseWithRegex(string valueString, result = default; if (!double.TryParse(valueString, ParseNumberStyles, formatProvider, out var value)) - { - return false; - } + return false; if (!_unitParser.TryParse(unitString, formatProvider, out var parsedUnit)) - { - return false; - } + return false; result = fromDelegate(value, parsedUnit); return true; diff --git a/UnitsNet/CustomCode/UnitAbbreviationsCache.cs b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs index 689e2937a8..d10b08b5fe 100644 --- a/UnitsNet/CustomCode/UnitAbbreviationsCache.cs +++ b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs @@ -8,6 +8,7 @@ using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; + using UnitTypeToLookup = System.Collections.Generic.Dictionary; // ReSharper disable once CheckNamespace @@ -15,13 +16,14 @@ namespace UnitsNet { /// /// Cache of the mapping between unit enum values and unit abbreviation strings for one or more cultures. - /// A static instance is used internally for ToString() and Parse() of quantities and units. + /// A static instance is used internally for ToString() and Parse() of quantities and units. /// public sealed partial class UnitAbbreviationsCache { + private readonly Dictionary _lookupsForCulture; + /// - /// Fallback culture used by and - /// + /// Fallback culture used by and /// if no abbreviations are found with a given culture. /// /// @@ -31,12 +33,10 @@ public sealed partial class UnitAbbreviationsCache /// private static readonly CultureInfo FallbackCulture = new CultureInfo("en-US"); - private readonly Dictionary _lookupsForCulture; - - static UnitAbbreviationsCache() - { - Default = new UnitAbbreviationsCache(); - } + /// + /// The static instance used internally for ToString() and Parse() of quantities and units. + /// + public static UnitAbbreviationsCache Default { get; } /// /// Create an instance of the cache and load all the abbreviations defined in the library. @@ -48,14 +48,14 @@ public UnitAbbreviationsCache() LoadGeneratedAbbreviations(); } - /// - /// The static instance used internally for ToString() and Parse() of quantities and units. - /// - public static UnitAbbreviationsCache Default { get; } + static UnitAbbreviationsCache() + { + Default = new UnitAbbreviationsCache(); + } private void LoadGeneratedAbbreviations() { - foreach (var localization in GeneratedLocalizations) + foreach(var localization in GeneratedLocalizations) { var culture = new CultureInfo(localization.CultureName); MapUnitToAbbreviation(localization.UnitType, localization.UnitValue, culture, localization.UnitAbbreviations); @@ -63,11 +63,9 @@ private void LoadGeneratedAbbreviations() } /// - /// Adds one or more unit abbreviation for the given unit enum value. - /// This is used to dynamically add abbreviations for existing unit enums such as - /// or to extend with third-party unit enums - /// in order to or on them - /// later. + /// Adds one or more unit abbreviation for the given unit enum value. + /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums + /// in order to or on them later. /// /// The unit enum value. /// Unit abbreviations to add. @@ -79,11 +77,9 @@ public void MapUnitToAbbreviation(TUnitType unit, params string[] abb } /// - /// Adds a unit abbreviation for the given unit enum value and sets it as the default. - /// This is used to dynamically add abbreviations for existing unit enums such as - /// or to extend with third-party unit enums - /// in order to or on them - /// later. + /// Adds a unit abbreviation for the given unit enum value and sets it as the default. + /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums + /// in order to or on them later. /// /// The unit enum value. /// Unit abbreviations to add as default. @@ -94,17 +90,12 @@ public void MapUnitToDefaultAbbreviation(TUnitType unit, string abbre } /// - /// Adds one or more unit abbreviation for the given unit enum value. - /// This is used to dynamically add abbreviations for existing unit enums such as or to - /// extend with third-party unit enums - /// in order to or on them - /// later. + /// Adds one or more unit abbreviation for the given unit enum value. + /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums + /// in order to or on them later. /// /// The unit enum value. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations to add. /// The type of unit enum. [PublicAPI] @@ -120,17 +111,12 @@ public void MapUnitToAbbreviation(TUnitType unit, IFormatProvider for } /// - /// Adds a unit abbreviation for the given unit enum value and sets it as the default. - /// This is used to dynamically add abbreviations for existing unit enums such as or to - /// extend with third-party unit enums - /// in order to or on them - /// later. + /// Adds a unit abbreviation for the given unit enum value and sets it as the default. + /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums + /// in order to or on them later. /// /// The unit enum value. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviation to add as default. /// The type of unit enum. [PublicAPI] @@ -146,18 +132,13 @@ public void MapUnitToDefaultAbbreviation(TUnitType unit, IFormatProvi } /// - /// Adds one or more unit abbreviation for the given unit enum value. - /// This is used to dynamically add abbreviations for existing unit enums such as or to - /// extend with third-party unit enums - /// in order to or on them - /// later. + /// Adds one or more unit abbreviation for the given unit enum value. + /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums + /// in order to or on them later. /// /// The unit enum type. /// The unit enum value. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations to add. [PublicAPI] public void MapUnitToAbbreviation(Type unitType, int unitValue, IFormatProvider formatProvider, [NotNull] params string[] abbreviations) @@ -166,18 +147,13 @@ public void MapUnitToAbbreviation(Type unitType, int unitValue, IFormatProvider } /// - /// Adds a unit abbreviation for the given unit enum value and sets it as the default. - /// This is used to dynamically add abbreviations for existing unit enums such as or to - /// extend with third-party unit enums - /// in order to or on them - /// later. + /// Adds a unit abbreviation for the given unit enum value and sets it as the default. + /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums + /// in order to or on them later. /// /// The unit enum type. /// The unit enum value. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviation to add as default. [PublicAPI] public void MapUnitToDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider formatProvider, [NotNull] string abbreviation) @@ -185,30 +161,21 @@ public void MapUnitToDefaultAbbreviation(Type unitType, int unitValue, IFormatPr PerformAbbreviationMapping(unitType, unitValue, formatProvider, true, abbreviation); } - private void PerformAbbreviationMapping(Type unitType, int unitValue, IFormatProvider formatProvider, bool setAsDefault, - [NotNull] params string[] abbreviations) + private void PerformAbbreviationMapping(Type unitType, int unitValue, IFormatProvider formatProvider, bool setAsDefault, [NotNull] params string[] abbreviations) { if (!unitType.Wrap().IsEnum) - { throw new ArgumentException("Must be an enum type.", nameof(unitType)); - } if (abbreviations == null) - { throw new ArgumentNullException(nameof(abbreviations)); - } formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; if (!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) - { quantitiesForProvider = _lookupsForCulture[formatProvider] = new UnitTypeToLookup(); - } if (!quantitiesForProvider.TryGetValue(unitType, out var unitToAbbreviations)) - { unitToAbbreviations = quantitiesForProvider[unitType] = new UnitValueAbbreviationLookup(); - } foreach (var abbr in abbreviations) { @@ -217,15 +184,11 @@ private void PerformAbbreviationMapping(Type unitType, int unitValue, IFormatPro } /// - /// Gets the default abbreviation for a given unit. If a unit has more than one abbreviation defined, then it returns - /// the first one. - /// Example: GetDefaultAbbreviation<LengthUnit>(LengthUnit.Kilometer) => "km" + /// Gets the default abbreviation for a given unit. If a unit has more than one abbreviation defined, then it returns the first one. + /// Example: GetDefaultAbbreviation<LengthUnit>(LengthUnit.Kilometer) => "km" /// /// The unit enum value. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// The type of unit enum. /// The default unit abbreviation string. [PublicAPI] @@ -233,64 +196,53 @@ public string GetDefaultAbbreviation(TUnitType unit, IFormatProvider { var unitType = typeof(TUnitType); - if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) + if(!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) { - if (formatProvider != FallbackCulture) - { + if(formatProvider != FallbackCulture) return GetDefaultAbbreviation(unit, FallbackCulture); - } - - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); + else + throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); } var abbreviations = lookup.GetAbbreviationsForUnit(unit); - if (abbreviations.Count == 0) + if(abbreviations.Count == 0) { - if (formatProvider != FallbackCulture) - { + if(formatProvider != FallbackCulture) return GetDefaultAbbreviation(unit, FallbackCulture); - } - - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); + else + throw new NotImplementedException($"No abbreviation is specified for {unitType.Name}.{unit}"); } return abbreviations.First(); } /// - /// Gets the default abbreviation for a given unit type and its numeric enum value. - /// If a unit has more than one abbreviation defined, then it returns the first one. - /// Example: GetDefaultAbbreviation<LengthUnit>(typeof(LengthUnit), 1) => "cm" + /// Gets the default abbreviation for a given unit type and its numeric enum value. + /// If a unit has more than one abbreviation defined, then it returns the first one. + /// Example: GetDefaultAbbreviation<LengthUnit>(typeof(LengthUnit), 1) => "cm" /// /// The unit enum type. /// The unit enum value. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// The default unit abbreviation string. [PublicAPI] public string GetDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider formatProvider = null) { - if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) + if(!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) { - if (formatProvider != FallbackCulture) - { + if(formatProvider != FallbackCulture) return GetDefaultAbbreviation(unitType, unitValue, FallbackCulture); - } - - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); + else + throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); } var abbreviations = lookup.GetAbbreviationsForUnit(unitValue); - if (abbreviations.Count == 0) + if(abbreviations.Count == 0) { - if (formatProvider != FallbackCulture) - { + if(formatProvider != FallbackCulture) return GetDefaultAbbreviation(unitType, unitValue, FallbackCulture); - } - - throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); + else + throw new NotImplementedException($"No abbreviation is specified for {unitType.Name} with numeric value {unitValue}."); } return abbreviations.First(); @@ -301,10 +253,7 @@ public string GetDefaultAbbreviation(Type unitType, int unitValue, IFormatProvid /// /// Enum type for units. /// Enum value for unit. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations associated with unit. [PublicAPI] public string[] GetUnitAbbreviations(TUnitType unit, IFormatProvider formatProvider = null) where TUnitType : Enum @@ -317,26 +266,19 @@ public string[] GetUnitAbbreviations(TUnitType unit, IFormatProvider /// /// Enum type for unit. /// Enum value for unit. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations associated with unit. [PublicAPI] public string[] GetUnitAbbreviations(Type unitType, int unitValue, IFormatProvider formatProvider = null) { formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; - if (!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) - { + if(!TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var lookup)) return formatProvider != FallbackCulture ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) : new string[] { }; - } var abbreviations = lookup.GetAbbreviationsForUnit(unitValue); - if (abbreviations.Count == 0) - { + if(abbreviations.Count == 0) return formatProvider != FallbackCulture ? GetUnitAbbreviations(unitType, unitValue, FallbackCulture) : new string[] { }; - } return abbreviations.ToArray(); } @@ -345,20 +287,15 @@ public string[] GetUnitAbbreviations(Type unitType, int unitValue, IFormatProvid /// Get all abbreviations for all units of a quantity. /// /// Enum type for unit. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations associated with unit. [PublicAPI] public string[] GetAllUnitAbbreviationsForQuantity(Type unitEnumType, IFormatProvider formatProvider = null) { formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; - if (!TryGetUnitValueAbbreviationLookup(unitEnumType, formatProvider, out var lookup)) - { + if(!TryGetUnitValueAbbreviationLookup(unitEnumType, formatProvider, out var lookup)) return formatProvider != FallbackCulture ? GetAllUnitAbbreviationsForQuantity(unitEnumType, FallbackCulture) : new string[] { }; - } return lookup.GetAllUnitAbbreviationsForQuantity(); } @@ -369,15 +306,11 @@ internal bool TryGetUnitValueAbbreviationLookup(Type unitType, IFormatProvider f formatProvider = formatProvider ?? CultureInfo.CurrentUICulture; - if (!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) - { + if(!_lookupsForCulture.TryGetValue(formatProvider, out var quantitiesForProvider)) return formatProvider != FallbackCulture ? TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations) : false; - } - if (!quantitiesForProvider.TryGetValue(unitType, out unitToAbbreviations)) - { + if(!quantitiesForProvider.TryGetValue(unitType, out unitToAbbreviations)) return formatProvider != FallbackCulture ? TryGetUnitValueAbbreviationLookup(unitType, FallbackCulture, out unitToAbbreviations) : false; - } return true; } diff --git a/UnitsNet/CustomCode/UnitParser.cs b/UnitsNet/CustomCode/UnitParser.cs index a621a1c770..ef254232a4 100644 --- a/UnitsNet/CustomCode/UnitParser.cs +++ b/UnitsNet/CustomCode/UnitParser.cs @@ -12,17 +12,18 @@ namespace UnitsNet { /// /// Parses units given a unit abbreviations cache. - /// The static instance is used internally to parse quantities and units using the + /// The static instance is used internally to parse quantities and units using the /// default abbreviations cache for all units and abbreviations defined in the library. /// public sealed class UnitParser { private readonly UnitAbbreviationsCache _unitAbbreviationsCache; - static UnitParser() - { - Default = new UnitParser(UnitAbbreviationsCache.Default); - } + /// + /// The default static instance used internally to parse quantities and units using the + /// default abbreviations cache for all units and abbreviations defined in the library. + /// + public static UnitParser Default { get; } /// /// Create a parser using the given unit abbreviations cache. @@ -33,27 +34,23 @@ public UnitParser(UnitAbbreviationsCache unitAbbreviationsCache) _unitAbbreviationsCache = unitAbbreviationsCache ?? UnitAbbreviationsCache.Default; } - /// - /// The default static instance used internally to parse quantities and units using the - /// default abbreviations cache for all units and abbreviations defined in the library. - /// - public static UnitParser Default { get; } + static UnitParser() + { + Default = new UnitParser(UnitAbbreviationsCache.Default); + } /// - /// Parses a unit abbreviation for a given unit enumeration type. - /// Example: Parse<LengthUnit>("km") => LengthUnit.Kilometer + /// Parses a unit abbreviation for a given unit enumeration type. + /// Example: Parse<LengthUnit>("km") => LengthUnit.Kilometer /// /// - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// /// [PublicAPI] public TUnitType Parse(string unitAbbreviation, [CanBeNull] IFormatProvider formatProvider = null) where TUnitType : Enum { - return (TUnitType) Parse(unitAbbreviation, typeof(TUnitType), formatProvider); + return (TUnitType)Parse(unitAbbreviation, typeof(TUnitType), formatProvider); } /// @@ -65,10 +62,7 @@ public TUnitType Parse(string unitAbbreviation, [CanBeNull] IFormatPr /// respectively. /// /// Unit enum type, such as and . - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// Unit enum value, such as . /// No units match the abbreviation. /// More than one unit matches the abbreviation. @@ -78,24 +72,20 @@ public Enum Parse([NotNull] string unitAbbreviation, Type unitType, [CanBeNull] if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); unitAbbreviation = unitAbbreviation.Trim(); - if (!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) - { + if(!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) throw new UnitNotFoundException($"No abbreviations defined for unit type [{unitType}] for culture [{formatProvider}]."); - } - var unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, true); + var unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); if (unitIntValues.Count == 0) { unitAbbreviation = NormalizeUnitString(unitAbbreviation); - unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, true); + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); } // Narrow the search if too many hits, for example Megabar "Mbar" and Millibar "mbar" need to be distinguished if (unitIntValues.Count > 1) - { - unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, false); - } + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: false); switch (unitIntValues.Count) { @@ -104,7 +94,7 @@ public Enum Parse([NotNull] string unitAbbreviation, Type unitType, [CanBeNull] case 0: throw new UnitNotFoundException($"Unit not found with abbreviation [{unitAbbreviation}] for unit type [{unitType}]."); default: - var unitsCsv = string.Join(", ", unitIntValues.Select(x => Enum.GetName(unitType, x)).ToArray()); + string unitsCsv = string.Join(", ", unitIntValues.Select(x => Enum.GetName(unitType, x)).ToArray()); throw new AmbiguousUnitParseException( $"Cannot parse \"{unitAbbreviation}\" since it could be either of these: {unitsCsv}"); } @@ -142,7 +132,7 @@ internal static string NormalizeUnitString(string unitAbbreviation) } /// - /// Try to parse a unit abbreviation. + /// Try to parse a unit abbreviation. /// /// The string value. /// The unit enum value as out result. @@ -155,13 +145,10 @@ public bool TryParse(string unitAbbreviation, out TUnitType unit) whe } /// - /// Try to parse a unit abbreviation. + /// Try to parse a unit abbreviation. /// /// The string value. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// The unit enum value as out result. /// Type of unit enum. /// True if successful. @@ -170,17 +157,15 @@ public bool TryParse(string unitAbbreviation, [CanBeNull] IFormatProv { unit = default; - if (!TryParse(unitAbbreviation, typeof(TUnitType), formatProvider, out var unitObj)) - { + if(!TryParse(unitAbbreviation, typeof(TUnitType), formatProvider, out var unitObj)) return false; - } - unit = (TUnitType) unitObj; + unit = (TUnitType)unitObj; return true; } /// - /// Try to parse a unit abbreviation. + /// Try to parse a unit abbreviation. /// /// The string value. /// Type of unit enum. @@ -193,14 +178,11 @@ public bool TryParse(string unitAbbreviation, Type unitType, out Enum unit) } /// - /// Try to parse a unit abbreviation. + /// Try to parse a unit abbreviation. /// /// The string value. /// Type of unit enum. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// + /// The format provider to use for lookup. Defaults to if null. /// The unit enum value as out result. /// True if successful. [PublicAPI] @@ -215,31 +197,25 @@ public bool TryParse(string unitAbbreviation, Type unitType, [CanBeNull] IFormat unitAbbreviation = unitAbbreviation.Trim(); unit = default; - if (!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) - { + if(!_unitAbbreviationsCache.TryGetUnitValueAbbreviationLookup(unitType, formatProvider, out var abbreviations)) return false; - } - var unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, true); + var unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); if (unitIntValues.Count == 0) { unitAbbreviation = NormalizeUnitString(unitAbbreviation); - unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, true); + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: true); } // Narrow the search if too many hits, for example Megabar "Mbar" and Millibar "mbar" need to be distinguished if (unitIntValues.Count > 1) - { - unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, false); - } + unitIntValues = abbreviations.GetUnitsForAbbreviation(unitAbbreviation, ignoreCase: false); - if (unitIntValues.Count != 1) - { + if(unitIntValues.Count != 1) return false; - } - unit = (Enum) Enum.ToObject(unitType, unitIntValues[0]); + unit = (Enum)Enum.ToObject(unitType, unitIntValues[0]); return true; } } diff --git a/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs b/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs index 2336d6de97..a82d3f7faf 100644 --- a/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs +++ b/UnitsNet/CustomCode/UnitValueAbbreviationLookup.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; + using UnitToAbbreviationMap = System.Collections.Generic.Dictionary>; using AbbreviationToUnitMap = System.Collections.Generic.Dictionary>; @@ -11,13 +12,16 @@ namespace UnitsNet { internal class UnitValueAbbreviationLookup { + private readonly UnitToAbbreviationMap unitToAbbreviationMap = new UnitToAbbreviationMap(); private readonly AbbreviationToUnitMap abbreviationToUnitMap = new AbbreviationToUnitMap(); private readonly AbbreviationToUnitMap lowerCaseAbbreviationToUnitMap = new AbbreviationToUnitMap(); - private readonly UnitToAbbreviationMap unitToAbbreviationMap = new UnitToAbbreviationMap(); internal string[] GetAllUnitAbbreviationsForQuantity() { - return unitToAbbreviationMap.Values.SelectMany(abbreviations => { return abbreviations; }).Distinct().ToArray(); + return unitToAbbreviationMap.Values.SelectMany((abbreviations) => + { + return abbreviations; + } ).Distinct().ToArray(); } internal List GetAbbreviationsForUnit(UnitType unit) where UnitType : Enum @@ -27,10 +31,8 @@ internal List GetAbbreviationsForUnit(UnitType unit) where Uni internal List GetAbbreviationsForUnit(int unit) { - if (!unitToAbbreviationMap.TryGetValue(unit, out var abbreviations)) - { + if(!unitToAbbreviationMap.TryGetValue(unit, out var abbreviations)) unitToAbbreviationMap[unit] = abbreviations = new List(); - } return abbreviations.Distinct().ToList(); } @@ -41,10 +43,8 @@ internal List GetUnitsForAbbreviation(string abbreviation, bool ignoreCase) var key = ignoreCase ? lowerCaseAbbreviation : abbreviation; var map = ignoreCase ? lowerCaseAbbreviationToUnitMap : abbreviationToUnitMap; - if (!map.TryGetValue(key, out var units)) - { + if(!map.TryGetValue(key, out List units)) map[key] = units = new List(); - } return units.Distinct().ToList(); } @@ -53,20 +53,14 @@ internal void Add(int unit, string abbreviation, bool setAsDefault = false) { var lowerCaseAbbreviation = abbreviation.ToLower(); - if (!unitToAbbreviationMap.TryGetValue(unit, out var abbreviationsForUnit)) - { + if(!unitToAbbreviationMap.TryGetValue(unit, out var abbreviationsForUnit)) abbreviationsForUnit = unitToAbbreviationMap[unit] = new List(); - } - if (!abbreviationToUnitMap.TryGetValue(abbreviation, out var unitsForAbbreviation)) - { + if(!abbreviationToUnitMap.TryGetValue(abbreviation, out var unitsForAbbreviation)) abbreviationToUnitMap[abbreviation] = unitsForAbbreviation = new List(); - } - if (!lowerCaseAbbreviationToUnitMap.TryGetValue(lowerCaseAbbreviation, out var unitsForLowerCaseAbbreviation)) - { + if(!lowerCaseAbbreviationToUnitMap.TryGetValue(lowerCaseAbbreviation, out var unitsForLowerCaseAbbreviation)) lowerCaseAbbreviationToUnitMap[lowerCaseAbbreviation] = unitsForLowerCaseAbbreviation = new List(); - } unitsForLowerCaseAbbreviation.Remove(unit); unitsForLowerCaseAbbreviation.Add(unit); @@ -76,13 +70,10 @@ internal void Add(int unit, string abbreviation, bool setAsDefault = false) abbreviationsForUnit.Remove(abbreviation); if (setAsDefault) - { abbreviationsForUnit.Insert(0, abbreviation); - } else - { abbreviationsForUnit.Add(abbreviation); - } + } } } diff --git a/UnitsNet/CustomCode/Units/PressureReference.cs b/UnitsNet/CustomCode/Units/PressureUnit.g.cs similarity index 100% rename from UnitsNet/CustomCode/Units/PressureReference.cs rename to UnitsNet/CustomCode/Units/PressureUnit.g.cs diff --git a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs similarity index 97% rename from UnitsNet/CustomCode/Wrappers/ReferencePressure.cs rename to UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs index 682d14a619..d33ce141f0 100644 --- a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs +++ b/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs @@ -25,20 +25,6 @@ namespace UnitsNet.CustomCode.Wrappers /// public struct ReferencePressure { - /// - /// Represents the pressure at which _pressure is referenced (1 atm default) - /// - public static Pressure AtmosphericPressure { get; set; } - - private static readonly Pressure DefaultAtmosphericPressure = new Pressure(1, PressureUnit.Atmosphere); - - /// - /// Gets a list of options: , - /// , and - /// - public static List References { get; } = - Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); - /// /// Initializes a new instance of the struct requiring measured /// @@ -59,7 +45,7 @@ public ReferencePressure(Pressure pressure) : this(pressure, BaseReference) /// /// The referenced for the measured /// - public ReferencePressure(Pressure pressure, PressureReference reference) : this(pressure, reference, DefaultAtmosphericPressure) + public ReferencePressure(Pressure pressure, PressureReference reference) : this(pressure, reference, _defaultAtmosphericPressure) { } @@ -85,6 +71,13 @@ public ReferencePressure(Pressure pressure, PressureReference reference, Pressur /// public PressureReference Reference { get; } + /// + /// Gets a list of options: , + /// , and + /// + public static List References { get; } = + Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); + /// /// The base reference representation of for the numeric value stored internally. All /// conversions go via @@ -190,5 +183,12 @@ private double AsBaseReference() throw new NotImplementedException($"Can not convert {Reference} to base reference."); } } + + /// + /// Represents the pressure at which _pressure is referenced (1 atm default) + /// + public static Pressure AtmosphericPressure { get; set; } + + private static readonly Pressure _defaultAtmosphericPressure = new Pressure(1, PressureUnit.Atmosphere); } } diff --git a/UnitsNet/IQuantity.cs b/UnitsNet/IQuantity.cs index 862afaa029..60f522e93f 100644 --- a/UnitsNet/IQuantity.cs +++ b/UnitsNet/IQuantity.cs @@ -28,53 +28,44 @@ public interface IQuantity : IFormattable /// QuantityInfo QuantityInfo { get; } - /// - /// The unit this quantity was constructed with -or- BaseUnit if default ctor was used. - /// - Enum Unit { get; } - - /// - /// The value this quantity was constructed with. See also . - /// - double Value { get; } - /// /// Gets the value in the given unit. /// - /// - /// The unit enum value. The unit must be compatible, so for you should provide a - /// value. - /// + /// The unit enum value. The unit must be compatible, so for you should provide a value. /// Value converted to the specified unit. /// Wrong unit enum type was given. double As(Enum unit); /// - /// Gets the value in the unit determined by the given . If multiple units were found for the - /// given , + /// Gets the value in the unit determined by the given . If multiple units were found for the given , /// the first match will be used. /// - /// The to convert the quantity value to. + /// The to convert the quantity value to. /// The converted value. double As(UnitSystem unitSystem); /// - /// Converts to a quantity with the given unit representation, which affects things like - /// . + /// The unit this quantity was constructed with -or- BaseUnit if default ctor was used. + /// + Enum Unit { get; } + + /// + /// The value this quantity was constructed with. See also . /// - /// - /// The unit enum value. The unit must be compatible, so for you should provide a - /// value. - /// + double Value { get; } + + /// + /// Converts to a quantity with the given unit representation, which affects things like . + /// + /// The unit enum value. The unit must be compatible, so for you should provide a value. /// A new quantity with the given unit. IQuantity ToUnit(Enum unit); /// - /// Converts to a quantity with a unit determined by the given , which affects things like - /// . - /// If multiple units were found for the given , the first match will be used. + /// Converts to a quantity with a unit determined by the given , which affects things like . + /// If multiple units were found for the given , the first match will be used. /// - /// The to convert the quantity to. + /// The to convert the quantity to. /// A new quantity with the determined unit. IQuantity ToUnit(UnitSystem unitSystem); @@ -82,10 +73,7 @@ public interface IQuantity : IFormattable /// Gets the string representation of value and unit. Uses two significant digits after radix. /// /// String representation. - /// - /// Format to use for localization and number formatting. Defaults to - /// if null. - /// + /// Format to use for localization and number formatting. Defaults to if null. string ToString([CanBeNull] IFormatProvider provider); /// @@ -93,12 +81,8 @@ public interface IQuantity : IFormattable /// /// The number of significant digits after the radix point. /// String representation. - /// - /// Format to use for localization and number formatting. Defaults to - /// if null. - /// - [Obsolete( - @"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] + /// Format to use for localization and number formatting. Defaults to if null. + [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix); /// @@ -107,17 +91,14 @@ public interface IQuantity : IFormattable /// 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. - /// - /// Format to use for localization and number formatting. Defaults to - /// if null. - /// + /// Format to use for localization and number formatting. Defaults to if null. [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args); } /// /// A stronger typed interface where the unit enum type is known, to avoid passing in the - /// wrong unit enum type and not having to cast from . + /// wrong unit enum type and not having to cast from . /// /// /// IQuantity{LengthUnit} length; @@ -125,32 +106,30 @@ public interface IQuantity : IFormattable /// public interface IQuantity : IQuantity where TUnitType : Enum { - /// - new TUnitType Unit { get; } - - /// - new QuantityInfo QuantityInfo { get; } - /// - /// Convert to a unit representation . + /// Convert to a unit representation . /// /// Value converted to the specified unit. double As(TUnitType unit); + /// + new TUnitType Unit { get; } + + /// + new QuantityInfo QuantityInfo { get; } + /// - /// Converts to a quantity with the given unit representation, which affects things like - /// . + /// Converts to a quantity with the given unit representation, which affects things like . /// /// The unit enum value. /// A new quantity with the given unit. IQuantity ToUnit(TUnitType unit); /// - /// Converts to a quantity with a unit determined by the given , which affects things like - /// . - /// If multiple units were found for the given , the first match will be used. + /// Converts to a quantity with a unit determined by the given , which affects things like . + /// If multiple units were found for the given , the first match will be used. /// - /// The to convert the quantity to. + /// The to convert the quantity to. /// A new quantity with the determined unit. new IQuantity ToUnit(UnitSystem unitSystem); } diff --git a/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs b/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs index 95423d683a..0232e43834 100644 --- a/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs +++ b/UnitsNet/InternalHelpers/ReflectionBridgeExtensions.cs @@ -1,14 +1,14 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using System; +using System.Collections.Generic; +using System.Reflection; #if NET40 || NET35 || NET20 || SILVERLIGHT using UniformTypeInfo = System.Type; #else using UniformTypeInfo = System.Reflection.TypeInfo; #endif -using System; -using System.Collections.Generic; -using System.Reflection; // Based on // https://github.com/StefH/ReflectionBridge/blob/c1e34e57fe3fc93507e83d5cebc1677396645397/ReflectionBridge/src/ReflectionBridge/Extensions/ReflectionBridgeExtensions.cs @@ -47,11 +47,9 @@ internal IEnumerable GetDeclaredMethods() #if NET40 || NET35 || NET20 || SILVERLIGHT foreach (MethodInfo m in t.GetMethods()) #else - foreach (var m in t.DeclaredMethods) + foreach (MethodInfo m in t.DeclaredMethods) #endif - { yield return m; - } t = t.BaseType?.ToUniformType(); } diff --git a/UnitsNet/QuantityFormatter.cs b/UnitsNet/QuantityFormatter.cs index c70af40a89..782c2de23c 100644 --- a/UnitsNet/QuantityFormatter.cs +++ b/UnitsNet/QuantityFormatter.cs @@ -9,33 +9,29 @@ namespace UnitsNet { /// - /// The QuantityFormatter class is responsible for formatting a quantity using the given format string. + /// The QuantityFormatter class is responsible for formatting a quantity using the given format string. /// public class QuantityFormatter { /// - /// Formats the given quantity using the given format string and format provider. + /// Formats the given quantity using the given format string and format provider. /// - /// The quantity's unit type, for example . + /// The quantity's unit type, for example . /// The quantity to format. /// The format string. - /// - /// The format provider to use for localization and number formatting. Defaults to - /// if null. - /// + /// The format provider to use for localization and number formatting. Defaults to + /// if null. /// - /// The valid format strings are as follows: - /// "g": The value with 2 significant digits after the radix followed by the unit abbreviation, such as "1.23 m". - /// "a": The default unit abbreviation for , such as "m". - /// "a0", "a1", ..., "aN": The Nth unit abbreviation for . "a0" is the same as - /// "a". - /// A will be thrown if the requested abbreviation index does not exist. - /// "v": String representation of . - /// "u": The enum name of , such as "Meter". - /// "q": The quantity name, such as "Length". - /// "s1", "s2", ..., "sN": The value with N significant digits after the radix followed by the unit abbreviation. For - /// example, - /// "s4" would return "1.2345 m" if is 1.2345678. Trailing zeros are omitted. + /// The valid format strings are as follows: + /// "g": The value with 2 significant digits after the radix followed by the unit abbreviation, such as "1.23 m". + /// "a": The default unit abbreviation for , such as "m". + /// "a0", "a1", ..., "aN": The Nth unit abbreviation for . "a0" is the same as "a". + /// A will be thrown if the requested abbreviation index does not exist. + /// "v": String representation of . + /// "u": The enum name of , such as "Meter". + /// "q": The quantity name, such as "Length". + /// "s1", "s2", ..., "sN": The value with N significant digits after the radix followed by the unit abbreviation. For example, + /// "s4" would return "1.2345 m" if is 1.2345678. Trailing zeros are omitted. /// /// The string representation. public static string Format(IQuantity quantity, string format, IFormatProvider formatProvider) @@ -46,32 +42,26 @@ public static string Format(IQuantity quantity, string for var number = 0; var formatString = format; - if (string.IsNullOrEmpty(formatString)) - { + if(string.IsNullOrEmpty(formatString)) formatString = "g"; - } - if (formatString.StartsWith("a") || formatString.StartsWith("s")) + if(formatString.StartsWith("a") || formatString.StartsWith("s")) { - if (formatString.Length > 1 && !int.TryParse(formatString.Substring(1), out number)) - { + if(formatString.Length > 1 && !int.TryParse(formatString.Substring(1), out number)) throw new FormatException($"The {format} format string is not supported."); - } formatString = formatString.Substring(0, 1); } - switch (formatString) + switch(formatString) { case "g": return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, 2); case "a": var abbreviations = UnitAbbreviationsCache.Default.GetUnitAbbreviations(quantity.Unit, formatProvider); - if (number >= abbreviations.Length) - { + if(number >= abbreviations.Length) throw new FormatException($"The {format} format string is invalid because the abbreviation index does not exist."); - } return abbreviations[number]; case "v": @@ -87,11 +77,10 @@ public static string Format(IQuantity quantity, string for } } - private static string ToStringWithSignificantDigitsAfterRadix(IQuantity quantity, IFormatProvider formatProvider, int number) - where TUnitType : Enum + private static string ToStringWithSignificantDigitsAfterRadix(IQuantity quantity, IFormatProvider formatProvider, int number) where TUnitType : Enum { - var formatForSignificantDigits = UnitFormatter.GetFormat(quantity.Value, number); - var formatArgs = UnitFormatter.GetFormatArgs(quantity.Unit, quantity.Value, formatProvider, Enumerable.Empty()); + string formatForSignificantDigits = UnitFormatter.GetFormat(quantity.Value, number); + object[] formatArgs = UnitFormatter.GetFormatArgs(quantity.Unit, quantity.Value, formatProvider, Enumerable.Empty()); return string.Format(formatProvider, formatForSignificantDigits, formatArgs); } } diff --git a/UnitsNet/QuantityInfo.cs b/UnitsNet/QuantityInfo.cs index edeea6b988..2dcdd4cb21 100644 --- a/UnitsNet/QuantityInfo.cs +++ b/UnitsNet/QuantityInfo.cs @@ -40,11 +40,10 @@ public class QuantityInfo /// The base dimensions of the quantity. /// Quantity type can not be undefined. /// If units -or- baseUnit -or- zero -or- baseDimensions is null. - public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [NotNull] Enum baseUnit, [NotNull] IQuantity zero, - [NotNull] BaseDimensions baseDimensions) + public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [NotNull] Enum baseUnit, [NotNull] IQuantity zero, [NotNull] BaseDimensions baseDimensions) { - if (quantityType == QuantityType.Undefined) throw new ArgumentException("Quantity type can not be undefined.", nameof(quantityType)); - if (baseUnit == null) throw new ArgumentNullException(nameof(baseUnit)); + if(quantityType == QuantityType.Undefined) throw new ArgumentException("Quantity type can not be undefined.", nameof(quantityType)); + if(baseUnit == null) throw new ArgumentNullException(nameof(baseUnit)); BaseDimensions = baseDimensions ?? throw new ArgumentNullException(nameof(baseDimensions)); Zero = zero ?? throw new ArgumentNullException(nameof(zero)); @@ -61,8 +60,8 @@ public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [ // Obsolete members #pragma warning disable 618 - UnitNames = UnitInfos.Select(unitInfo => unitInfo.Name).ToArray(); - Units = UnitInfos.Select(unitInfo => unitInfo.Value).ToArray(); + UnitNames = UnitInfos.Select( unitInfo => unitInfo.Name ).ToArray(); + Units = UnitInfos.Select( unitInfo => unitInfo.Value ).ToArray(); BaseUnit = BaseUnitInfo.Value; #pragma warning restore 618 } @@ -112,12 +111,12 @@ public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [ public IQuantity Zero { get; } /// - /// Unit enum type, such as or . + /// Unit enum type, such as or . /// public Type UnitType { get; } /// - /// Quantity value type, such as or . + /// Quantity value type, such as or . /// public Type ValueType { get; } @@ -127,29 +126,18 @@ public QuantityInfo(QuantityType quantityType, [NotNull] UnitInfo[] unitInfos, [ public BaseDimensions BaseDimensions { get; } /// - /// Gets the whose is a subset of . + /// Gets the whose is a subset of . /// - /// - /// Length.Info.GetUnitInfoFor(unitSystemWithFootAsLengthUnit) returns for - /// . - /// - /// The to check against. - /// - /// The that has that is a subset of - /// . - /// - /// is null. - /// No unit was found that is a subset of . - /// - /// More than one unit was found that is a subset of - /// . - /// + /// Length.Info.GetUnitInfoFor(unitSystemWithFootAsLengthUnit) returns for . + /// The to check against. + /// The that has that is a subset of . + /// is null. + /// No unit was found that is a subset of . + /// More than one unit was found that is a subset of . public UnitInfo GetUnitInfoFor(BaseUnits baseUnits) { - if (baseUnits == null) - { + if(baseUnits == null) throw new ArgumentNullException(nameof(baseUnits)); - } var matchingUnitInfos = GetUnitInfosFor(baseUnits) .Take(2) @@ -157,36 +145,26 @@ public UnitInfo GetUnitInfoFor(BaseUnits baseUnits) var firstUnitInfo = matchingUnitInfos.FirstOrDefault(); if (firstUnitInfo == null) - { throw new InvalidOperationException($"No unit was found that is a subset of {nameof(baseUnits)}"); - } if (matchingUnitInfos.Length > 1) - { throw new InvalidOperationException($"More than one unit was found that is a subset of {nameof(baseUnits)}"); - } return firstUnitInfo; } /// - /// Gets an of that have that is a - /// subset of . + /// Gets an of that have that is a subset of . /// - /// The to check against. - /// - /// An of that have that is a - /// subset of . - /// - /// is null. + /// The to check against. + /// An of that have that is a subset of . + /// is null. public IEnumerable GetUnitInfosFor(BaseUnits baseUnits) { - if (baseUnits == null) - { + if(baseUnits == null) throw new ArgumentNullException(nameof(baseUnits)); - } - return UnitInfos.Where(unitInfo => unitInfo.BaseUnits.IsSubsetOf(baseUnits)); + return UnitInfos.Where((unitInfo) => unitInfo.BaseUnits.IsSubsetOf(baseUnits)); } } @@ -210,7 +188,7 @@ public QuantityInfo(QuantityType quantityType, UnitInfo[] unitInfos, TUni // Obsolete members #pragma warning disable 618 - Units = UnitInfos.Select(unitInfo => unitInfo.Value).ToArray(); + Units = UnitInfos.Select( unitInfo => unitInfo.Value ).ToArray(); BaseUnit = BaseUnitInfo.Value; #pragma warning restore 618 } @@ -238,7 +216,7 @@ public QuantityInfo(QuantityType quantityType, UnitInfo[] unitInfos, TUni /// public new UnitInfo GetUnitInfoFor(BaseUnits baseUnits) { - return (UnitInfo) base.GetUnitInfoFor(baseUnits); + return (UnitInfo)base.GetUnitInfoFor(baseUnits); } /// diff --git a/UnitsNet/QuantityTypeConverter.cs b/UnitsNet/QuantityTypeConverter.cs index a54b0dd25c..63bb261d7e 100644 --- a/UnitsNet/QuantityTypeConverter.cs +++ b/UnitsNet/QuantityTypeConverter.cs @@ -8,120 +8,118 @@ namespace UnitsNet { /// - /// Is the base class for all attributes that are related to + /// Is the base class for all attributes that are related to /// - [AttributeUsage(AttributeTargets.Property)] + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public abstract class UnitAttributeBase : Attribute { /// - /// Initializes a new instance of the class. + /// The unit enum type, such as + /// + public Enum UnitType { get; set; } + + /// + /// Initializes a new instance of the class. /// /// public UnitAttributeBase(object unitType) { UnitType = unitType as Enum; } - - /// - /// The unit enum type, such as - /// - public Enum UnitType { get; set; } } /// - /// This attribute defines the default Unit to use if the string to convert only consists of digits + /// This attribute defines the default Unit to use if the string to convert only consists of digits /// public class DefaultUnitAttribute : UnitAttributeBase { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The unit the quantity gets when the string parsing dose only consist of digits - public DefaultUnitAttribute(object unitType) : base(unitType) - { - } + public DefaultUnitAttribute(object unitType) : base(unitType) { } } /// - /// This attribute defines the Unit the quantity is converted to after it has been parsed. + /// This attribute defines the Unit the quantity is converted to after it has been parsed. /// public class ConvertToUnitAttribute : DefaultUnitAttribute { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The unit the quantity is converted to when parsing from string - public ConvertToUnitAttribute(object unitType) : base(unitType) - { - } + public ConvertToUnitAttribute(object unitType) : base(unitType) { } } /// - /// This attribute defines the unit the quantity has when converting to string + /// This attribute defines the unit the quantity has when converting to string /// public class DisplayAsUnitAttribute : DefaultUnitAttribute { /// - /// Initializes a new instance of the class. + /// The formating used when the quantity is converted to string. See + /// + public string Format { get; set; } + + /// + /// Initializes a new instance of the class. /// /// The unit the quantity should be displayed in - /// Formating string + /// Formating string public DisplayAsUnitAttribute(object unitType, string format = "") : base(unitType) { Format = format; } - - /// - /// The formating used when the quantity is converted to string. See - /// - /// - public string Format { get; set; } } /// - /// - /// Converts between IQuantity and string. - /// Implements a TypeConverter for IQuantitys. This allows eg the PropertyGrid to read and write properties of type - /// IQuantity. - /// - /// For basic understanding of TypeConverters consult the .NET documentation. + /// + /// Converts between IQuantity and string. + /// Implements a TypeConverter for IQuantitys. This allows eg the PropertyGrid to read and write properties of type IQuantity. + /// + /// For basic understanding of TypeConverters consult the .NET documentation. /// - /// Quantity value type, such as or . + /// Quantity value type, such as or . /// - /// - /// When a string is converted a Quantity the unit given by the string is used. - /// When no unit is given by the string the base unit is used. - /// The base unit can be overwritten by use of the . - /// The converted Quantity can be forced to be in a certain unit by use of the - /// . - /// - /// - /// The displayed unit can be forced to a certain unit by use of the . - /// The provides the possibility to format the displayed Quantity. - /// + /// + /// When a string is converted a Quantity the unit given by the string is used. + /// When no unit is given by the string the base unit is used. + /// The base unit can be overwritten by use of the . + /// The converted Quantity can be forced to be in a certain unit by use of the . + /// + /// + /// The displayed unit can be forced to a certain unit by use of the . + /// The provides the possibility to format the displayed Quantity. + /// /// /// - /// These examples show how to use this TypeConverter. - /// + /// These examples show how to use this TypeConverter. + /// + /// /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length PropertyName { get; set; } /// - /// + /// + /// /// [DisplayAsUnit(UnitsNet.Units.LengthUnit.Meter)] /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length Length { get; set; } /// - /// + /// + /// /// [DisplayAsUnit(UnitsNet.Units.LengthUnit.Meter, "g")] /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length Length { get; set; } /// - /// + /// + /// /// [ConvertToUnitAttribute(UnitsNet.Units.LengthUnit.Meter)] /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length Length { get; set; } /// - /// + /// + /// /// [DefaultUnitAttribute(UnitsNet.Units.LengthUnit.Meter)] /// [TypeConverter(typeof(UnitsNetTypeConverter{Length}))] /// Units.Length Length { get; set; } @@ -130,27 +128,27 @@ public DisplayAsUnitAttribute(object unitType, string format = "") : base(unitTy public class QuantityTypeConverter : TypeConverter where TQuantity : IQuantity { /// - /// Returns true if sourceType if of type + /// Returns true if sourceType if of type /// - /// An that provides a format context. - /// A that represents the type you want to convert from. + /// An that provides a format context. + /// A that represents the type you want to convert from. /// true if this converter can perform the conversion; otherwise, false. public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); + return (sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType); } private static TAttribute GetAttribute(ITypeDescriptorContext context) where TAttribute : UnitAttributeBase { TAttribute attribute = null; - var ua = context?.PropertyDescriptor.Attributes; + AttributeCollection ua = context?.PropertyDescriptor.Attributes; - attribute = (TAttribute) ua?[typeof(TAttribute)]; + attribute = (TAttribute)ua?[typeof(TAttribute)]; if (attribute != null) { - var expected = default(TQuantity).Type; - var actual = QuantityType.Undefined; + QuantityType expected = default(TQuantity).Type; + QuantityType actual = QuantityType.Undefined; if (attribute.UnitType != null) actual = Quantity.From(1, attribute.UnitType).Type; if (actual != QuantityType.Undefined && expected != actual) @@ -163,25 +161,24 @@ private static TAttribute GetAttribute(ITypeDescriptorContext contex } /// - /// Converts the given object, when it is of type to the type of this converter, using the - /// specified context and culture information. + /// Converts the given object, when it is of type to the type of this converter, using the specified context and culture information. /// /// An System.ComponentModel.ITypeDescriptorContext that provides a format context. /// The System.Globalization.CultureInfo to use as the current culture. /// The System.Object to convert. - /// An object. + /// An object. /// The conversion cannot be performed. /// Unit value is not a know unit enum type. public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - var stringValue = value as string; + string stringValue = value as string; object result = null; if (!string.IsNullOrEmpty(stringValue)) { - if (double.TryParse(stringValue, NumberStyles.Any, culture, out var dvalue)) + if (double.TryParse(stringValue, NumberStyles.Any, culture, out double dvalue)) { - var defaultUnit = GetAttribute(context) ?? new DefaultUnitAttribute(default(TQuantity).Unit); + DefaultUnitAttribute defaultUnit = GetAttribute(context) ?? new DefaultUnitAttribute(default(TQuantity).Unit); result = Quantity.From(dvalue, defaultUnit.UnitType); } @@ -190,47 +187,38 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c result = Quantity.Parse(culture, typeof(TQuantity), stringValue); } - var convertToUnit = GetAttribute(context); + ConvertToUnitAttribute convertToUnit = GetAttribute(context); if (convertToUnit != null) { - result = ((IQuantity) result).ToUnit(convertToUnit.UnitType); + result = ((IQuantity)result).ToUnit(convertToUnit.UnitType); } } return result ?? base.ConvertFrom(context, culture, value); } - /// - /// Returns true whether this converter can convert the to string, using the specified - /// context. - /// + /// Returns true whether this converter can convert the to string, using the specified context. /// true if this converter can perform the conversion; otherwise, false. /// An that provides a format context. /// A that represents the type you want to convert to. public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); + return (destinationType == typeof(string)) || base.CanConvertTo(context, destinationType); } - /// - /// Converts the given object to , using the specified context and - /// culture information. - /// + /// Converts the given object to , using the specified context and culture information. /// An that represents the converted value. /// An that provides a format context. - /// - /// A . If null is passed, the current culture is - /// assumed. - /// + /// A . If null is passed, the current culture is assumed. /// The to convert. /// The to convert the parameter to. /// The parameter is null. /// The conversion cannot be performed. public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - var qvalue = value as IQuantity; + IQuantity qvalue = value as IQuantity; object result = null; - var displayAsUnit = GetAttribute(context); + DisplayAsUnitAttribute displayAsUnit = GetAttribute(context); if (destinationType == typeof(string) && qvalue != null && displayAsUnit != null) { diff --git a/UnitsNet/QuantityValue.cs b/UnitsNet/QuantityValue.cs index 8c395fdb08..66ad890316 100644 --- a/UnitsNet/QuantityValue.cs +++ b/UnitsNet/QuantityValue.cs @@ -8,16 +8,11 @@ namespace UnitsNet /// /// A type that supports implicit cast from all .NET numeric types, in order to avoid a large number of overloads /// and binary size for all From(value, unit) factory methods, for each of the 700+ units in the library. - /// stores the value internally with the proper type to preserve the range or precision of - /// the original value: - /// - /// - /// for [byte, short, int, long, float, double] - /// - /// - /// for [decimal] to preserve the 128-bit precision - /// - /// + /// stores the value internally with the proper type to preserve the range or precision of the original value: + /// + /// for [byte, short, int, long, float, double] + /// for [decimal] to preserve the 128-bit precision + /// /// /// /// At the time of this writing, this reduces the number of From(value, unit) overloads to 1/4th: @@ -28,13 +23,13 @@ public struct QuantityValue { /// /// Value assigned when implicitly casting from all numeric types except , since - /// has the greatest range and is 64 bits versus 128 bits for . + /// has the greatest range and is 64 bits versus 128 bits for . /// private readonly double? _value; /// /// Value assigned when implicitly casting from type, since it has a greater precision than - /// and we want to preserve that when constructing quantities that use + /// and we want to preserve that when constructing quantities that use /// as their value type. /// private readonly decimal? _valueDecimal; @@ -57,25 +52,19 @@ private QuantityValue(decimal val) // Prefer double for integer types, since most quantities use that type as of now and // that avoids unnecessary casts back and forth. // If we later change to use decimal more, we should revisit this. - /// Implicit cast from to . + /// Implicit cast from to . public static implicit operator QuantityValue(byte val) => new QuantityValue((double) val); - - /// Implicit cast from to . + /// Implicit cast from to . public static implicit operator QuantityValue(short val) => new QuantityValue((double) val); - - /// Implicit cast from to . + /// Implicit cast from to . public static implicit operator QuantityValue(int val) => new QuantityValue((double) val); - - /// Implicit cast from to . + /// Implicit cast from to . public static implicit operator QuantityValue(long val) => new QuantityValue((double) val); - - /// Implicit cast from to . + /// Implicit cast from to . public static implicit operator QuantityValue(float val) => new QuantityValue(val); // double - - /// Implicit cast from to . + /// Implicit cast from to . public static implicit operator QuantityValue(double val) => new QuantityValue(val); // double - - /// Implicit cast from to . + /// Implicit cast from to . public static implicit operator QuantityValue(decimal val) => new QuantityValue(val); // decimal #pragma warning restore 618 @@ -83,7 +72,7 @@ private QuantityValue(decimal val) #region To double - /// Explicit cast from to . + /// Explicit cast from to . public static explicit operator double(QuantityValue number) { // double -> decimal -> zero (since we can't implement the default struct ctor) @@ -94,7 +83,7 @@ public static explicit operator double(QuantityValue number) #region To decimal - /// Explicit cast from to . + /// Explicit cast from to . public static explicit operator decimal(QuantityValue number) { // decimal -> double -> zero (since we can't implement the default struct ctor) diff --git a/UnitsNet/UnitConverter.cs b/UnitsNet/UnitConverter.cs index 68a08853c3..b9641f03ce 100644 --- a/UnitsNet/UnitConverter.cs +++ b/UnitsNet/UnitConverter.cs @@ -13,12 +13,14 @@ namespace UnitsNet using ConversionFunctionLookupKey = ValueTuple; /// + /// /// /// /// public delegate IQuantity ConversionFunction(IQuantity inputValue); /// + /// /// /// /// @@ -32,8 +34,13 @@ public delegate TQuantity ConversionFunction(TQuantity inputValue) [PublicAPI] public sealed partial class UnitConverter { - private readonly Dictionary _conversionFunctions = - new Dictionary(); + /// + /// The static instance used by Units.NET to convert between units. Modify this to add/remove conversion functions at runtime, such + /// as adding your own third-party units and quantities to convert between. + /// + public static UnitConverter Default { get; } + + private readonly Dictionary _conversionFunctions = new Dictionary(); static UnitConverter() { @@ -42,18 +49,11 @@ static UnitConverter() } /// - /// The static instance used by Units.NET to convert between units. Modify this to add/remove conversion functions at - /// runtime, such - /// as adding your own third-party units and quantities to convert between. + /// Sets the conversion function from two units of the same quantity type. /// - public static UnitConverter Default { get; } - - /// - /// Sets the conversion function from two units of the same quantity type. - /// - /// The type of quantity, must implement . + /// The type of quantity, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// The quantity conversion function. public void SetConversionFunction(Enum from, Enum to, ConversionFunction conversionFunction) where TQuantity : IQuantity @@ -64,12 +64,12 @@ public void SetConversionFunction(Enum from, Enum to, ConversionFunct } /// - /// Sets the conversion function from two units of different quantity types. + /// Sets the conversion function from two units of different quantity types. /// - /// From quantity type, must implement . - /// To quantity type, must implement . + /// From quantity type, must implement . + /// To quantity type, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// The quantity conversion function. public void SetConversionFunction(Enum from, Enum to, ConversionFunction conversionFunction) where TQuantityFrom : IQuantity @@ -79,12 +79,12 @@ public void SetConversionFunction(Enum from, Enum to } /// - /// Sets the conversion function from two units of different quantity types. + /// Sets the conversion function from two units of different quantity types. /// - /// From quantity type, must implement . + /// From quantity type, must implement . /// From unit enum value, such as . - /// To quantity type, must implement . - /// To unit enum value, such as . + /// To quantity type, must implement . + /// To unit enum value, such as . /// The quantity conversion function. public void SetConversionFunction(Type fromType, Enum from, Type toType, Enum to, ConversionFunction conversionFunction) { @@ -93,7 +93,7 @@ public void SetConversionFunction(Type fromType, Enum from, Type toType, Enum to } /// - /// Sets the conversion function for a particular conversion function lookup. + /// Sets the conversion function for a particular conversion function lookup. /// /// The lookup key. /// The quantity conversion function. @@ -103,28 +103,25 @@ internal void SetConversionFunction(ConversionFunctionLookupKey lookupKey, Conve } /// - /// Sets the conversion function for a particular conversion function lookup. + /// Sets the conversion function for a particular conversion function lookup. /// - /// The quantity type, must implement . + /// The quantity type, must implement . /// The quantity conversion function lookup key. /// The quantity conversion function. internal void SetConversionFunction(ConversionFunctionLookupKey conversionLookup, ConversionFunction conversionFunction) where TQuantity : IQuantity { - IQuantity TypelessConversionFunction(IQuantity quantity) - { - return conversionFunction((TQuantity) quantity); - } + IQuantity TypelessConversionFunction(IQuantity quantity) => conversionFunction((TQuantity) quantity); _conversionFunctions[conversionLookup] = TypelessConversionFunction; } /// - /// Gets the conversion function from two units of the same quantity type. + /// Gets the conversion function from two units of the same quantity type. /// - /// The quantity type, must implement . + /// The quantity type, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// public ConversionFunction GetConversionFunction(Enum from, Enum to) where TQuantity : IQuantity { @@ -132,12 +129,12 @@ public ConversionFunction GetConversionFunction(Enum from, Enum to) w } /// - /// Gets the conversion function from two units of different quantity types. + /// Gets the conversion function from two units of different quantity types. /// - /// From quantity type, must implement . - /// To quantity type, must implement . + /// From quantity type, must implement . + /// To quantity type, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// public ConversionFunction GetConversionFunction(Enum from, Enum to) where TQuantityFrom : IQuantity @@ -147,12 +144,12 @@ public ConversionFunction GetConversionFunction(Enum } /// - /// Gets the conversion function from two units of different quantity types. + /// Gets the conversion function from two units of different quantity types. /// - /// From quantity type, must implement . + /// From quantity type, must implement . /// From unit enum value, such as . - /// To quantity type, must implement . - /// To unit enum value, such as . + /// To quantity type, must implement . + /// To unit enum value, such as . public ConversionFunction GetConversionFunction(Type fromType, Enum from, Type toType, Enum to) { var conversionLookup = new ConversionFunctionLookupKey(fromType, from, toType, to); @@ -160,32 +157,27 @@ public ConversionFunction GetConversionFunction(Type fromType, Enum from, Type t } /// - /// Gets the conversion function by its lookup key. + /// Gets the conversion function by its lookup key. /// /// internal ConversionFunction GetConversionFunction(ConversionFunctionLookupKey lookupKey) { - IQuantity EchoFunction(IQuantity fromQuantity) - { - return fromQuantity; - } + IQuantity EchoFunction(IQuantity fromQuantity) => fromQuantity; // If from/to units and to quantity types are equal, then return a function that echoes the input quantity // in order to not have to map conversion functions to "self". if (lookupKey.Item1 == lookupKey.Item3 && Equals(lookupKey.Item2, lookupKey.Item4)) - { return EchoFunction; - } return _conversionFunctions[lookupKey]; } /// - /// Gets the conversion function for two units of the same quantity type. + /// Gets the conversion function for two units of the same quantity type. /// - /// The quantity type, must implement . + /// The quantity type, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// The quantity conversion function. /// true if set; otherwise, false. public bool TryGetConversionFunction(Enum from, Enum to, out ConversionFunction conversionFunction) where TQuantity : IQuantity @@ -194,12 +186,12 @@ public bool TryGetConversionFunction(Enum from, Enum to, out Conversi } /// - /// Gets the conversion function for two units of different quantity types. + /// Gets the conversion function for two units of different quantity types. /// - /// From quantity type, must implement . - /// To quantity type, must implement . + /// From quantity type, must implement . + /// To quantity type, must implement . /// From unit enum value, such as . - /// To unit enum value, such as . + /// To unit enum value, such as . /// The quantity conversion function. /// true if set; otherwise, false. public bool TryGetConversionFunction(Enum from, Enum to, out ConversionFunction conversionFunction) @@ -210,12 +202,12 @@ public bool TryGetConversionFunction(Enum from, Enum } /// - /// Try to get the conversion function for two units of the same quantity type. + /// Try to get the conversion function for two units of the same quantity type. /// - /// From quantity type, must implement . + /// From quantity type, must implement . /// From unit enum value, such as . - /// To quantity type, must implement . - /// To unit enum value, such as . + /// To quantity type, must implement . + /// To unit enum value, such as . /// The quantity conversion function. /// true if set; otherwise, false. public bool TryGetConversionFunction(Type fromType, Enum from, Type toType, Enum to, out ConversionFunction conversionFunction) @@ -225,6 +217,7 @@ public bool TryGetConversionFunction(Type fromType, Enum from, Type toType, Enum } /// + /// /// /// /// @@ -259,7 +252,7 @@ public static double Convert(QuantityValue fromValue, Enum fromUnitValue, Enum t public static bool TryConvert(QuantityValue fromValue, Enum fromUnitValue, Enum toUnitValue, out double convertedValue) { convertedValue = 0; - if (!Quantity.TryFrom(fromValue, fromUnitValue, out var fromQuantity)) return false; + if (!Quantity.TryFrom(fromValue, fromUnitValue, out IQuantity fromQuantity)) return false; try { @@ -303,19 +296,17 @@ public static bool TryConvert(QuantityValue fromValue, Enum fromUnitValue, Enum /// More than one unit matches the abbreviation. public static double ConvertByName(QuantityValue fromValue, string quantityName, string fromUnit, string toUnit) { - if (!TryGetUnitType(quantityName, out var unitType)) - { + if (!TryGetUnitType(quantityName, out Type unitType)) throw new UnitNotFoundException($"The unit type for the given quantity was not found: {quantityName}"); - } - if (!TryParseUnit(unitType, fromUnit, out var fromUnitValue)) // ex: LengthUnit.Meter + if (!TryParseUnit(unitType, fromUnit, out Enum fromUnitValue)) // ex: LengthUnit.Meter { var e = new UnitNotFoundException($"Unit not found [{fromUnit}]."); e.Data["unitName"] = fromUnit; throw e; } - if (!TryParseUnit(unitType, toUnit, out var toUnitValue)) // ex: LengthUnit.Centimeter + if (!TryParseUnit(unitType, toUnit, out Enum toUnitValue)) // ex: LengthUnit.Centimeter { var e = new UnitNotFoundException($"Unit not found [{toUnit}]."); e.Data["unitName"] = toUnit; @@ -356,20 +347,14 @@ public static bool TryConvertByName(QuantityValue inputValue, string quantityNam { result = 0d; - if (!TryGetUnitType(quantityName, out var unitType)) - { + if (!TryGetUnitType(quantityName, out Type unitType)) return false; - } - if (!TryParseUnit(unitType, fromUnit, out var fromUnitValue)) // ex: LengthUnit.Meter - { + if (!TryParseUnit(unitType, fromUnit, out Enum fromUnitValue)) // ex: LengthUnit.Meter return false; - } - if (!TryParseUnit(unitType, toUnit, out var toUnitValue)) // ex: LengthUnit.Centimeter - { + if (!TryParseUnit(unitType, toUnit, out Enum toUnitValue)) // ex: LengthUnit.Centimeter return false; - } result = Convert(inputValue, fromUnitValue, toUnitValue); return true; @@ -440,10 +425,8 @@ public static double ConvertByAbbreviation(QuantityValue fromValue, string quant /// More than one unit matches the abbreviation. public static double ConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, string culture) { - if (!TryGetUnitType(quantityName, out var unitType)) - { + if (!TryGetUnitType(quantityName, out Type unitType)) throw new UnitNotFoundException($"The unit type for the given quantity was not found: {quantityName}"); - } var cultureInfo = string.IsNullOrWhiteSpace(culture) ? CultureInfo.CurrentUICulture : new CultureInfo(culture); @@ -519,22 +502,16 @@ public static bool TryConvertByAbbreviation(QuantityValue fromValue, string quan { result = 0d; - if (!TryGetUnitType(quantityName, out var unitType)) - { + if (!TryGetUnitType(quantityName, out Type unitType)) return false; - } var cultureInfo = string.IsNullOrWhiteSpace(culture) ? CultureInfo.CurrentUICulture : new CultureInfo(culture); - if (!UnitParser.Default.TryParse(fromUnitAbbrev, unitType, cultureInfo, out var fromUnit)) // ex: ("m", LengthUnit) => LengthUnit.Meter - { + if (!UnitParser.Default.TryParse(fromUnitAbbrev, unitType, cultureInfo, out Enum fromUnit)) // ex: ("m", LengthUnit) => LengthUnit.Meter return false; - } - if (!UnitParser.Default.TryParse(toUnitAbbrev, unitType, cultureInfo, out var toUnit)) // ex:("cm", LengthUnit) => LengthUnit.Centimeter - { + if (!UnitParser.Default.TryParse(toUnitAbbrev, unitType, cultureInfo, out Enum toUnit)) // ex:("cm", LengthUnit) => LengthUnit.Centimeter return false; - } var fromQuantity = Quantity.From(fromValue, fromUnit); result = fromQuantity.As(toUnit); @@ -556,9 +533,7 @@ private static bool TryParseUnit(Type unitType, string unitName, out Enum unitVa var eNames = Enum.GetNames(unitType); unitName = eNames.FirstOrDefault(x => x.Equals(unitName, StringComparison.OrdinalIgnoreCase)); if (unitName == null) - { return false; - } unitValue = (Enum) Enum.Parse(unitType, unitName); return true; @@ -566,10 +541,11 @@ private static bool TryParseUnit(Type unitType, string unitName, out Enum unitVa private static bool TryGetUnitType(string quantityName, out Type unitType) { - var quantityInfo = Quantity.Infos.FirstOrDefault(info => info.Name.Equals(quantityName, StringComparison.OrdinalIgnoreCase)); + var quantityInfo = Quantity.Infos.FirstOrDefault((info) => info.Name.Equals(quantityName, StringComparison.OrdinalIgnoreCase)); unitType = quantityInfo?.UnitType; return quantityInfo != null; } } } + diff --git a/UnitsNet/UnitFormatter.cs b/UnitsNet/UnitFormatter.cs index 5594634bc6..3e1259b718 100644 --- a/UnitsNet/UnitFormatter.cs +++ b/UnitsNet/UnitFormatter.cs @@ -24,7 +24,7 @@ internal static class UnitFormatter /// A ToString format for the specified value. public static string GetFormat(double value, int significantDigitsAfterRadix) { - var v = Math.Abs(value); + double v = Math.Abs(value); var sigDigitsAfterRadixStr = new string('#', significantDigitsAfterRadix); string format; @@ -38,12 +38,12 @@ public static string GetFormat(double value, int significantDigitsAfterRadix) format = "{0:0." + sigDigitsAfterRadixStr + "e-00} {1}"; } // Values from 1e-3 to 1 use fixed point notation. - else if (v > 1e-4 && v < 1) + else if ((v > 1e-4) && (v < 1)) { format = "{0:g" + significantDigitsAfterRadix + "} {1}"; } // Values between 1 and 1e5 use fixed point notation with digit grouping. - else if (v >= 1 && v < 1e6) + else if ((v >= 1) && (v < 1e6)) { // The comma will be automatically replaced with the correct digit separator if a different culture is used. format = "{0:#,0." + sigDigitsAfterRadixStr + "} {1}"; @@ -74,7 +74,7 @@ private static bool NearlyEqual(double a, double b) public static object[] GetFormatArgs(TUnitType unit, double value, [CanBeNull] IFormatProvider culture, IEnumerable args) where TUnitType : Enum { - var abbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(typeof(TUnitType), Convert.ToInt32(unit), culture); + string abbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(typeof(TUnitType), Convert.ToInt32(unit), culture); return new object[] {value, abbreviation}.Concat(args).ToArray(); } } diff --git a/UnitsNet/UnitInfo.cs b/UnitsNet/UnitInfo.cs index db73e31fe7..7f44311779 100644 --- a/UnitsNet/UnitInfo.cs +++ b/UnitsNet/UnitInfo.cs @@ -19,10 +19,10 @@ namespace UnitsNet public class UnitInfo { /// - /// Creates an instance of the UnitInfo class. + /// Creates an instance of the UnitInfo class. /// - /// The enum value for this class, for example . - /// The for this unit. + /// The enum value for this class, for example . + /// The for this unit. public UnitInfo([NotNull] Enum value, [NotNull] BaseUnits baseUnits) { Value = value ?? throw new ArgumentNullException(nameof(value)); @@ -31,18 +31,18 @@ public UnitInfo([NotNull] Enum value, [NotNull] BaseUnits baseUnits) } /// - /// The enum value of the unit, such as [, - /// , , ...]. + /// The enum value of the unit, such as [, + /// , , ...]. /// public Enum Value { get; } /// - /// The name of the unit, such as ["Centimeter", "Decimeter", "Meter", ...]. + /// The name of the unit, such as ["Centimeter", "Decimeter", "Meter", ...]. /// public string Name { get; } /// - /// Gets the for this unit. + /// Gets the for this unit. /// public BaseUnits BaseUnits { get; } } @@ -63,7 +63,7 @@ public UnitInfo(TUnit value, BaseUnits baseUnits) : base(value, baseUnits) Value = value; } - /// + /// public new TUnit Value { get; } } } diff --git a/UnitsNet/UnitMath.cs b/UnitsNet/UnitMath.cs index a9b03aa90c..2d1eec758a 100644 --- a/UnitsNet/UnitMath.cs +++ b/UnitsNet/UnitMath.cs @@ -1,7 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. -// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. - -using System; +using System; using System.Collections.Generic; using System.Linq; diff --git a/UnitsNet/UnitSystem.cs b/UnitsNet/UnitSystem.cs index fa42f39346..f55821b7ff 100644 --- a/UnitsNet/UnitSystem.cs +++ b/UnitsNet/UnitSystem.cs @@ -8,85 +8,63 @@ namespace UnitsNet { /// /// A unit system defined by a combination of base units. - /// This is typically used to define the "working units" for consistently creating and presenting quantities in the - /// selected base units, - /// such as to use SI base units such as meters, kilograms and seconds. + /// This is typically used to define the "working units" for consistently creating and presenting quantities in the selected base units, + /// such as to use SI base units such as meters, kilograms and seconds. /// public sealed class UnitSystem : IEquatable { - private static readonly BaseUnits SIBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - /// - /// Creates an instance of a unit system with the specified base units. + /// Creates an instance of a unit system with the specified base units. /// /// The base units for the unit system. public UnitSystem(BaseUnits baseUnits) { - if (baseUnits is null) - { + if(baseUnits is null) throw new ArgumentNullException(nameof(baseUnits)); - } - if (!baseUnits.IsFullyDefined) - { + if(!baseUnits.IsFullyDefined) throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); - } BaseUnits = baseUnits; } - /// - /// The base units of this unit system. - /// - public BaseUnits BaseUnits { get; } - - /// - /// Gets the SI unit system. - /// - public static UnitSystem SI { get; } = new UnitSystem(SIBaseUnits); - /// - public bool Equals(UnitSystem other) + public override bool Equals(object obj) { - if (other is null) - { + if(obj is null || !(obj is UnitSystem)) return false; - } - return BaseUnits.Equals(other.BaseUnits); + return Equals((UnitSystem)obj); } /// - public override bool Equals(object obj) + public bool Equals(UnitSystem other) { - if (obj is null || !(obj is UnitSystem)) - { + if(other is null) return false; - } - return Equals((UnitSystem) obj); + return BaseUnits.Equals(other.BaseUnits); } /// - /// Checks if this instance is equal to another. + /// Checks if this instance is equal to another. /// /// The left instance. /// The right instance. /// True if equal, otherwise false. - /// + /// public static bool operator ==(UnitSystem left, UnitSystem right) { return left is null ? right is null : left.Equals(right); } /// - /// Checks if this instance is equal to another. + /// Checks if this instance is equal to another. /// /// The left instance. /// The right instance. /// True if equal, otherwise false. - /// + /// public static bool operator !=(UnitSystem left, UnitSystem right) { return !(left == right); @@ -97,5 +75,18 @@ public override int GetHashCode() { return new {BaseUnits}.GetHashCode(); } + + /// + /// The base units of this unit system. + /// + public BaseUnits BaseUnits{ get; } + + private static readonly BaseUnits SIBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + + /// + /// Gets the SI unit system. + /// + public static UnitSystem SI { get; } = new UnitSystem(SIBaseUnits); } } From 2f7ef1eaa4deb064ac649bc3bbd7a8c46c4e710a Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 11 Dec 2019 11:55:40 -0600 Subject: [PATCH 21/24] Renamed .cs file and moved static methods. --- ...PressureUnit.g.cs => PressureReference.cs} | 0 ...essure.Wrapper.cs => ReferencePressure.cs} | 31 ++++++++++--------- 2 files changed, 16 insertions(+), 15 deletions(-) rename UnitsNet/CustomCode/Units/{PressureUnit.g.cs => PressureReference.cs} (100%) rename UnitsNet/CustomCode/Wrappers/{Pressure.Wrapper.cs => ReferencePressure.cs} (97%) diff --git a/UnitsNet/CustomCode/Units/PressureUnit.g.cs b/UnitsNet/CustomCode/Units/PressureReference.cs similarity index 100% rename from UnitsNet/CustomCode/Units/PressureUnit.g.cs rename to UnitsNet/CustomCode/Units/PressureReference.cs diff --git a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs similarity index 97% rename from UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs rename to UnitsNet/CustomCode/Wrappers/ReferencePressure.cs index d33ce141f0..f5ab23a7d3 100644 --- a/UnitsNet/CustomCode/Wrappers/Pressure.Wrapper.cs +++ b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs @@ -25,6 +25,21 @@ namespace UnitsNet.CustomCode.Wrappers /// public struct ReferencePressure { + /// + /// Represents the pressure at which _pressure is referenced (1 atm default) + /// + public static Pressure AtmosphericPressure { get; set; } + + private static readonly Pressure DefaultAtmosphericPressure = new Pressure(1, PressureUnit.Atmosphere); + + /// + /// Gets a list of options: , + /// , and + /// + public static List References { get; } = + Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); + + /// /// Initializes a new instance of the struct requiring measured /// @@ -45,7 +60,7 @@ public ReferencePressure(Pressure pressure) : this(pressure, BaseReference) /// /// The referenced for the measured /// - public ReferencePressure(Pressure pressure, PressureReference reference) : this(pressure, reference, _defaultAtmosphericPressure) + public ReferencePressure(Pressure pressure, PressureReference reference) : this(pressure, reference, DefaultAtmosphericPressure) { } @@ -71,13 +86,6 @@ public ReferencePressure(Pressure pressure, PressureReference reference, Pressur /// public PressureReference Reference { get; } - /// - /// Gets a list of options: , - /// , and - /// - public static List References { get; } = - Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); - /// /// The base reference representation of for the numeric value stored internally. All /// conversions go via @@ -183,12 +191,5 @@ private double AsBaseReference() throw new NotImplementedException($"Can not convert {Reference} to base reference."); } } - - /// - /// Represents the pressure at which _pressure is referenced (1 atm default) - /// - public static Pressure AtmosphericPressure { get; set; } - - private static readonly Pressure _defaultAtmosphericPressure = new Pressure(1, PressureUnit.Atmosphere); } } From afbc3b415d30a9eec6d373c6e4fdd5c277bec632 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 11 Dec 2019 12:41:25 -0600 Subject: [PATCH 22/24] Changes based on change request. --- .../CustomCode/Wrappers/ReferencePressure.cs | 75 ++++++++++--------- 1 file changed, 38 insertions(+), 37 deletions(-) diff --git a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs index f5ab23a7d3..dd4380c190 100644 --- a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs +++ b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs @@ -28,7 +28,7 @@ public struct ReferencePressure /// /// Represents the pressure at which _pressure is referenced (1 atm default) /// - public static Pressure AtmosphericPressure { get; set; } + public Pressure AtmosphericPressure { get; set; } private static readonly Pressure DefaultAtmosphericPressure = new Pressure(1, PressureUnit.Atmosphere); @@ -36,29 +36,28 @@ public struct ReferencePressure /// Gets a list of options: , /// , and /// - public static List References { get; } = + public static IReadOnlyList References { get; } = Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); - /// /// Initializes a new instance of the struct requiring measured - /// + /// /// parameter. Assumes the to , with 1 atm as - /// the atmospheric . + /// the atmospheric . /// - /// The measured absolute + /// The measured absolute public ReferencePressure(Pressure pressure) : this(pressure, BaseReference) { } /// /// Initializes a new instance of the struct requiring - /// measured and parameters. Assumes 1 atm as the atmospheric - /// . + /// measured and parameters. Assumes 1 atm as the atmospheric + /// . /// - /// The measured + /// The measured /// - /// The referenced for the measured + /// The referenced for the measured /// public ReferencePressure(Pressure pressure, PressureReference reference) : this(pressure, reference, DefaultAtmosphericPressure) { @@ -66,18 +65,18 @@ public ReferencePressure(Pressure pressure, PressureReference reference) : this( /// /// Initializes a new instance of the struct requiring - /// measured , , and atmospheric + /// measured , , and atmospheric /// parameters /// - /// The measured + /// The measured /// - /// The referenced for the measured + /// The referenced for the measured /// - /// The atmospheric where the measurement was taken. + /// The atmospheric where the measurement was taken. public ReferencePressure(Pressure pressure, PressureReference reference, Pressure atmosphericPressure) { Reference = reference; - _pressure = pressure; + Pressure = pressure; AtmosphericPressure = atmosphericPressure; } @@ -88,45 +87,47 @@ public ReferencePressure(Pressure pressure, PressureReference reference, Pressur /// /// The base reference representation of for the numeric value stored internally. All - /// conversions go via - /// this value. + /// conversions go via this value. /// public const PressureReference BaseReference = PressureReference.Absolute; - private readonly Pressure _pressure; + /// + /// The at the given . + /// + public Pressure Pressure { get; } /// - /// Get Gauge . - /// It refers pressure level above Reference pressure. + /// Get Gauge . + /// It references pressure level above Atmospheric pressure. /// public Pressure Gauge => As(PressureReference.Gauge); /// - /// Get Absolute . + /// Get Absolute . /// It is zero-referenced pressure to the perfect vacuum. /// public Pressure Absolute => As(PressureReference.Absolute); /// - /// Get Vacuum . - /// It is a negative Gauge pressure when Absolute pressure is below Reference pressure. + /// Get Vacuum . + /// It is a negative Gauge pressure when Absolute pressure is below Atmospheric pressure. /// public Pressure Vacuum => As(PressureReference.Vacuum); /// - /// Converts to at + /// Converts to at /// /// The to convert to. - /// The at the specified + /// The at the specified private Pressure As(PressureReference reference) { var converted = AsBaseNumericType(reference); - return new Pressure(converted, _pressure.Unit); + return new Pressure(converted, Pressure.Unit); } /// - /// Converts to at + /// Converts to at /// /// The to convert to. /// The value of pressure at @@ -136,7 +137,7 @@ private double AsBaseNumericType(PressureReference reference) if (Reference == reference) { - return _pressure.Value; + return Pressure.Value; } var negatingValue = Reference == PressureReference.Vacuum ? -1 : 1; @@ -144,15 +145,15 @@ private double AsBaseNumericType(PressureReference reference) switch (reference) { case PressureReference.Absolute: return baseReferenceValue; - case PressureReference.Gauge: return baseReferenceValue - AtmosphericPressure.ToUnit(_pressure.Unit).Value; - case PressureReference.Vacuum: return AtmosphericPressure.ToUnit(_pressure.Unit).Value - negatingValue * baseReferenceValue; + case PressureReference.Gauge: return baseReferenceValue - AtmosphericPressure.ToUnit(Pressure.Unit).Value; + case PressureReference.Vacuum: return AtmosphericPressure.ToUnit(Pressure.Unit).Value - negatingValue * baseReferenceValue; default: throw new NotImplementedException($"Can not convert {Reference} to {reference}."); } } /// - /// Converts at to at + /// Converts at to at /// /// /// The value of pressure at the @@ -162,30 +163,30 @@ private double AsBaseReference() { case PressureReference.Absolute: { - if (_pressure.Value < 0) + if (Pressure.Value < 0) { throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); } - return _pressure.Value; + return Pressure.Value; } case PressureReference.Gauge: { - if (_pressure.Value * -1 > AtmosphericPressure.ToUnit(_pressure.Unit).Value) + if (Pressure.Value * -1 > AtmosphericPressure.ToUnit(Pressure.Unit).Value) { throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); } - return AtmosphericPressure.ToUnit(_pressure.Unit).Value + _pressure.Value; + return AtmosphericPressure.ToUnit(Pressure.Unit).Value + Pressure.Value; } case PressureReference.Vacuum: { - if (_pressure.Value > AtmosphericPressure.ToUnit(_pressure.Unit).Value) + if (Pressure.Value > AtmosphericPressure.ToUnit(Pressure.Unit).Value) { throw new ArgumentOutOfRangeException("Absolute pressure cannot be less than zero."); } - return AtmosphericPressure.ToUnit(_pressure.Unit).Value - _pressure.Value; + return AtmosphericPressure.ToUnit(Pressure.Unit).Value - Pressure.Value; } default: throw new NotImplementedException($"Can not convert {Reference} to base reference."); From 9db829d18d28130f9c6187cd247b5107c3a631cd Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 11 Dec 2019 13:08:32 -0600 Subject: [PATCH 23/24] Changed IReadonlyList back to List, as it is not compatible with .NET 4.0 --- UnitsNet/CustomCode/Wrappers/ReferencePressure.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs index dd4380c190..f015ec6b1f 100644 --- a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs +++ b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs @@ -36,7 +36,7 @@ public struct ReferencePressure /// Gets a list of options: , /// , and /// - public static IReadOnlyList References { get; } = + public static List References { get; } = Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); /// From 04e95346835d8c4010a2dc1541ca82bb98285de6 Mon Sep 17 00:00:00 2001 From: Chris Sequeira Date: Wed, 11 Dec 2019 14:34:37 -0600 Subject: [PATCH 24/24] Changed References from list to array to minimize user modification. --- UnitsNet/CustomCode/Wrappers/ReferencePressure.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs index f015ec6b1f..c11d4a34c9 100644 --- a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs +++ b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs @@ -36,8 +36,8 @@ public struct ReferencePressure /// Gets a list of options: , /// , and /// - public static List References { get; } = - Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToList(); + public static PressureReference[] References { get; } = + Enum.GetValues(typeof(PressureReference)).Cast().Except(new[] {PressureReference.Undefined}).ToArray(); /// /// Initializes a new instance of the struct requiring measured