From 6cd1891f4bbdef8dc067a2a8de570d90608710b8 Mon Sep 17 00:00:00 2001 From: Andreas Gullberg Larsen Date: Fri, 17 Jul 2026 18:02:59 +0200 Subject: [PATCH] Remove Scalar quantity --- Common/UnitDefinitions/Scalar.json | 19 - Common/UnitEnumValues.g.json | 3 - .../NumberToScalarExtensionsTest.g.cs | 32 - .../NumberToScalarExtensions.g.cs | 55 -- .../NumberToScalarExtensionsTest.g.cs | 32 - .../NumberToScalarExtensions.g.cs | 47 -- UnitsNet.Tests/CustomCode/ScalarTests.cs | 31 - .../GeneratedCode/IQuantityTests.g.cs | 2 - .../TestsBase/ScalarTestsBase.g.cs | 604 --------------- UnitsNet/GeneratedCode/Quantities/Scalar.g.cs | 726 ------------------ UnitsNet/GeneratedCode/Quantity.g.cs | 2 - .../GeneratedCode/Resources/Scalar.restext | 1 - UnitsNet/GeneratedCode/Units/ScalarUnit.g.cs | 32 - 13 files changed, 1586 deletions(-) delete mode 100644 Common/UnitDefinitions/Scalar.json delete mode 100644 UnitsNet.NumberExtensions.CS14.Tests/GeneratedCode/NumberToScalarExtensionsTest.g.cs delete mode 100644 UnitsNet.NumberExtensions.CS14/GeneratedCode/NumberToScalarExtensions.g.cs delete mode 100644 UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToScalarExtensionsTest.g.cs delete mode 100644 UnitsNet.NumberExtensions/GeneratedCode/NumberToScalarExtensions.g.cs delete mode 100644 UnitsNet.Tests/CustomCode/ScalarTests.cs delete mode 100644 UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs delete mode 100644 UnitsNet/GeneratedCode/Quantities/Scalar.g.cs delete mode 100644 UnitsNet/GeneratedCode/Resources/Scalar.restext delete mode 100644 UnitsNet/GeneratedCode/Units/ScalarUnit.g.cs diff --git a/Common/UnitDefinitions/Scalar.json b/Common/UnitDefinitions/Scalar.json deleted file mode 100644 index 8c8a5ebea4..0000000000 --- a/Common/UnitDefinitions/Scalar.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "Name": "Scalar", - "BaseUnit": "Amount", - "XmlDocSummary": "A way of representing a number of items.", - "Units": [ - { - "SingularName": "Amount", - "PluralName": "Amount", - "FromUnitToBaseFunc": "{x}", - "FromBaseToUnitFunc": "{x}", - "Localization": [ - { - "Culture": "en-US", - "Abbreviations": [ "" ] - } - ] - } - ] -} diff --git a/Common/UnitEnumValues.g.json b/Common/UnitEnumValues.g.json index 178c2b2055..4589f2e321 100644 --- a/Common/UnitEnumValues.g.json +++ b/Common/UnitEnumValues.g.json @@ -1329,9 +1329,6 @@ "NewtonMeterPerRadianPerMeter": 4, "PoundForceFootPerDegreesPerFoot": 5 }, - "Scalar": { - "Amount": 1 - }, "SolidAngle": { "Steradian": 1 }, diff --git a/UnitsNet.NumberExtensions.CS14.Tests/GeneratedCode/NumberToScalarExtensionsTest.g.cs b/UnitsNet.NumberExtensions.CS14.Tests/GeneratedCode/NumberToScalarExtensionsTest.g.cs deleted file mode 100644 index 8e49100470..0000000000 --- a/UnitsNet.NumberExtensions.CS14.Tests/GeneratedCode/NumberToScalarExtensionsTest.g.cs +++ /dev/null @@ -1,32 +0,0 @@ -//------------------------------------------------------------------------------ -// -// 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. - -using UnitsNet.NumberExtensions.NumberToScalar; -using Xunit; - -namespace UnitsNet.Tests -{ - public class NumberToScalarExtensionsTests - { - [Fact] - public void NumberToAmountTest() => - Assert.Equal(Scalar.FromAmount(2), 2.Amount); - - } -} diff --git a/UnitsNet.NumberExtensions.CS14/GeneratedCode/NumberToScalarExtensions.g.cs b/UnitsNet.NumberExtensions.CS14/GeneratedCode/NumberToScalarExtensions.g.cs deleted file mode 100644 index 62ce75ab9d..0000000000 --- a/UnitsNet.NumberExtensions.CS14/GeneratedCode/NumberToScalarExtensions.g.cs +++ /dev/null @@ -1,55 +0,0 @@ -//------------------------------------------------------------------------------ -// -// 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. - -using System; - -#if NET7_0_OR_GREATER -using System.Numerics; -#endif - -#nullable enable - -namespace UnitsNet.NumberExtensions.NumberToScalar -{ - /// - /// A number to Scalar Extensions - /// - public static class NumberToScalarExtensions - { -#pragma warning disable CS1591 - extension(T value) -#pragma warning restore CS1591 - where T : notnull -#if NET7_0_OR_GREATER - , INumber -#else - , IConvertible -#endif - { - /// - public Scalar Amount -#if NET7_0_OR_GREATER - => Scalar.FromAmount(double.CreateChecked(value)); -#else - => Scalar.FromAmount(value.ToDouble(null)); -#endif - - } - } -} diff --git a/UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToScalarExtensionsTest.g.cs b/UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToScalarExtensionsTest.g.cs deleted file mode 100644 index e18b87b7fe..0000000000 --- a/UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToScalarExtensionsTest.g.cs +++ /dev/null @@ -1,32 +0,0 @@ -//------------------------------------------------------------------------------ -// -// 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. - -using UnitsNet.NumberExtensions.NumberToScalar; -using Xunit; - -namespace UnitsNet.Tests -{ - public class NumberToScalarExtensionsTests - { - [Fact] - public void NumberToAmountTest() => - Assert.Equal(Scalar.FromAmount(2), 2.Amount()); - - } -} diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToScalarExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToScalarExtensions.g.cs deleted file mode 100644 index decb61c473..0000000000 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToScalarExtensions.g.cs +++ /dev/null @@ -1,47 +0,0 @@ -//------------------------------------------------------------------------------ -// -// 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. - -using System; - -#if NET7_0_OR_GREATER -using System.Numerics; -#endif - -#nullable enable - -namespace UnitsNet.NumberExtensions.NumberToScalar -{ - /// - /// A number to Scalar Extensions - /// - public static class NumberToScalarExtensions - { - /// - public static Scalar Amount(this T value) - where T : notnull -#if NET7_0_OR_GREATER - , INumber - => Scalar.FromAmount(double.CreateChecked(value)); -#else - , IConvertible - => Scalar.FromAmount(value.ToDouble(null)); -#endif - - } -} diff --git a/UnitsNet.Tests/CustomCode/ScalarTests.cs b/UnitsNet.Tests/CustomCode/ScalarTests.cs deleted file mode 100644 index 6c34cb39a0..0000000000 --- a/UnitsNet.Tests/CustomCode/ScalarTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -//------------------------------------------------------------------------------ -// -// 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. - -using System; -using Xunit; - -namespace UnitsNet.Tests.CustomCode -{ - public class ScalarTests : ScalarTestsBase - { - // Override properties in base class here - protected override double AmountInOneAmount => 1; - - } -} diff --git a/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs b/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs index 219abb6d52..c7f3b647f1 100644 --- a/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs +++ b/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs @@ -136,7 +136,6 @@ void Assertion(int expectedValue, Enum expectedUnit, IQuantity quantity) Assertion(3, RotationalSpeedUnit.RevolutionPerSecond, Quantity.From(3, RotationalSpeedUnit.RevolutionPerSecond)); Assertion(3, RotationalStiffnessUnit.PoundForceFootPerDegrees, Quantity.From(3, RotationalStiffnessUnit.PoundForceFootPerDegrees)); Assertion(3, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, Quantity.From(3, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot)); - Assertion(3, ScalarUnit.Amount, Quantity.From(3, ScalarUnit.Amount)); Assertion(3, SolidAngleUnit.Steradian, Quantity.From(3, SolidAngleUnit.Steradian)); Assertion(3, SpecificEnergyUnit.WattHourPerPound, Quantity.From(3, SpecificEnergyUnit.WattHourPerPound)); Assertion(3, SpecificEntropyUnit.MegajoulePerKilogramKelvin, Quantity.From(3, SpecificEntropyUnit.MegajoulePerKilogramKelvin)); @@ -271,7 +270,6 @@ public void QuantityInfo_IsSameAsStaticInfoProperty() Assertion(RotationalSpeed.Info, RotationalSpeed.Zero); Assertion(RotationalStiffness.Info, RotationalStiffness.Zero); Assertion(RotationalStiffnessPerLength.Info, RotationalStiffnessPerLength.Zero); - Assertion(Scalar.Info, Scalar.Zero); Assertion(SolidAngle.Info, SolidAngle.Zero); Assertion(SpecificEnergy.Info, SpecificEnergy.Zero); Assertion(SpecificEntropy.Info, SpecificEntropy.Zero); diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs deleted file mode 100644 index f1adb3c098..0000000000 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs +++ /dev/null @@ -1,604 +0,0 @@ -//------------------------------------------------------------------------------ -// -// 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. - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Threading; -using UnitsNet.InternalHelpers; -using UnitsNet.Tests.Helpers; -using UnitsNet.Tests.TestsBase; -using UnitsNet.Units; -using Xunit; - -// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else? -#pragma warning disable 1718 - -// ReSharper disable once CheckNamespace -namespace UnitsNet.Tests -{ - /// - /// Test of Scalar. - /// -// ReSharper disable once PartialTypeWithSinglePart - public abstract partial class ScalarTestsBase : QuantityTestsBase - { - protected abstract double AmountInOneAmount { get; } - -// ReSharper disable VirtualMemberNeverOverriden.Global - protected virtual double AmountTolerance { get { return 1e-5; } } -// ReSharper restore VirtualMemberNeverOverriden.Global - - protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(ScalarUnit unit) - { - return unit switch - { - ScalarUnit.Amount => (AmountInOneAmount, AmountTolerance), - _ => throw new NotSupportedException() - }; - } - - public static IEnumerable UnitTypes = new List - { - new object[] { ScalarUnit.Amount }, - }; - - [Fact] - public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() - { - var quantity = new Scalar(); - Assert.Equal(0, quantity.Value); - Assert.Equal(ScalarUnit.Amount, quantity.Unit); - } - - [Fact] - public void Ctor_WithInfinityValue_DoNotThrowsArgumentException() - { - var exception1 = Record.Exception(() => new Scalar(double.PositiveInfinity, ScalarUnit.Amount)); - var exception2 = Record.Exception(() => new Scalar(double.NegativeInfinity, ScalarUnit.Amount)); - - Assert.Null(exception1); - Assert.Null(exception2); - } - - [Fact] - public void Ctor_WithNaNValue_DoNotThrowsArgumentException() - { - var exception = Record.Exception(() => new Scalar(double.NaN, ScalarUnit.Amount)); - - Assert.Null(exception); - } - - [Fact] - public void Scalar_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() - { - ScalarUnit[] unitsOrderedByName = EnumHelper.GetValues().OrderBy(x => x.ToString(), StringComparer.OrdinalIgnoreCase).ToArray(); - var quantity = new Scalar(1, ScalarUnit.Amount); - - QuantityInfo quantityInfo = quantity.QuantityInfo; - - Assert.Equal("Scalar", quantityInfo.Name); - Assert.Equal(Scalar.Zero, quantityInfo.Zero); - Assert.Equal(Scalar.BaseUnit, quantityInfo.BaseUnitInfo.Value); - Assert.Equal(unitsOrderedByName, quantityInfo.Units); - Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); - Assert.Equal(Scalar.Info, quantityInfo); - Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); - Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); - } - - [Fact] - public void AmountToScalarUnits() - { - Scalar amount = Scalar.FromAmount(1); - AssertEx.EqualTolerance(AmountInOneAmount, amount.Amount, AmountTolerance); - } - - [Fact] - public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() - { - Assert.All(EnumHelper.GetValues(), unit => - { - var quantity = Scalar.From(1, unit); - Assert.Equal(1, quantity.Value); - Assert.Equal(unit, quantity.Unit); - }); - } - - [Fact] - public void FromAmount_WithInfinityValue_DoNotThrowsArgumentException() - { - var exception1 = Record.Exception(() => Scalar.FromAmount(double.PositiveInfinity)); - var exception2 = Record.Exception(() => Scalar.FromAmount(double.NegativeInfinity)); - - Assert.Null(exception1); - Assert.Null(exception2); - } - - [Fact] - public void FromAmount_WithNanValue_DoNotThrowsArgumentException() - { - var exception = Record.Exception(() => Scalar.FromAmount(double.NaN)); - - Assert.Null(exception); - } - - [Fact] - public void As() - { - var amount = Scalar.FromAmount(1); - AssertEx.EqualTolerance(AmountInOneAmount, amount.As(ScalarUnit.Amount), AmountTolerance); - } - - [Fact] - public void As_UnitSystem_ReturnsValueInDimensionlessUnit() - { - var quantity = new Scalar(value: 1, unit: ScalarUnit.Amount); - - var convertedValue = quantity.As(UnitSystem.SI); - - Assert.Equal(quantity.Value, convertedValue); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - var quantity = new Scalar(value: 1, unit: Scalar.BaseUnit); - UnitSystem nullUnitSystem = null!; - Assert.Throws(() => quantity.As(nullUnitSystem)); - } - - [Fact] - public void ToUnit_UnitSystem_ReturnsValueInDimensionlessUnit() - { - var quantity = new Scalar(value: 1, unit: ScalarUnit.Amount); - - Scalar convertedQuantity = quantity.ToUnit(UnitSystem.SI); - - Assert.Equal(ScalarUnit.Amount, convertedQuantity.Unit); - Assert.Equal(quantity.Value, convertedQuantity.Value); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - UnitSystem nullUnitSystem = null!; - Assert.Multiple(() => - { - var quantity = new Scalar(value: 1, unit: Scalar.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new Scalar(value: 1, unit: Scalar.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new Scalar(value: 1, unit: Scalar.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }); - } - - [Theory] - [InlineData("en-US", "4.2 ", ScalarUnit.Amount, 4.2)] - public void Parse(string culture, string quantityString, ScalarUnit expectedUnit, double expectedValue) - { - using var _ = new CultureScope(culture); - var parsed = Scalar.Parse(quantityString); - Assert.Equal(expectedUnit, parsed.Unit); - Assert.Equal(expectedValue, parsed.Value); - } - - [Theory] - [InlineData("en-US", "4.2 ", ScalarUnit.Amount, 4.2)] - public void TryParse(string culture, string quantityString, ScalarUnit expectedUnit, double expectedValue) - { - using var _ = new CultureScope(culture); - Assert.True(Scalar.TryParse(quantityString, out Scalar parsed)); - Assert.Equal(expectedUnit, parsed.Unit); - Assert.Equal(expectedValue, parsed.Value); - } - - [Theory] - [InlineData("", ScalarUnit.Amount)] - public void ParseUnit_WithUsEnglishCurrentCulture(string abbreviation, ScalarUnit expectedUnit) - { - // Fallback culture "en-US" is always localized - using var _ = new CultureScope("en-US"); - ScalarUnit parsedUnit = Scalar.ParseUnit(abbreviation); - Assert.Equal(expectedUnit, parsedUnit); - } - - [Theory] - [InlineData("", ScalarUnit.Amount)] - public void ParseUnit_WithUnsupportedCurrentCulture_FallsBackToUsEnglish(string abbreviation, ScalarUnit expectedUnit) - { - // Currently, no abbreviations are localized for Icelandic, so it should fall back to "en-US" when parsing. - using var _ = new CultureScope("is-IS"); - ScalarUnit parsedUnit = Scalar.ParseUnit(abbreviation); - Assert.Equal(expectedUnit, parsedUnit); - } - - [Theory] - [InlineData("en-US", "", ScalarUnit.Amount)] - public void ParseUnit_WithCurrentCulture(string culture, string abbreviation, ScalarUnit expectedUnit) - { - using var _ = new CultureScope(culture); - ScalarUnit parsedUnit = Scalar.ParseUnit(abbreviation); - Assert.Equal(expectedUnit, parsedUnit); - } - - [Theory] - [InlineData("en-US", "", ScalarUnit.Amount)] - public void ParseUnit_WithCulture(string culture, string abbreviation, ScalarUnit expectedUnit) - { - ScalarUnit parsedUnit = Scalar.ParseUnit(abbreviation, CultureInfo.GetCultureInfo(culture)); - Assert.Equal(expectedUnit, parsedUnit); - } - - [Theory] - [InlineData("", ScalarUnit.Amount)] - public void TryParseUnit_WithUsEnglishCurrentCulture(string abbreviation, ScalarUnit expectedUnit) - { - // Fallback culture "en-US" is always localized - using var _ = new CultureScope("en-US"); - Assert.True(Scalar.TryParseUnit(abbreviation, out ScalarUnit parsedUnit)); - Assert.Equal(expectedUnit, parsedUnit); - } - - [Theory] - [InlineData("", ScalarUnit.Amount)] - public void TryParseUnit_WithUnsupportedCurrentCulture_FallsBackToUsEnglish(string abbreviation, ScalarUnit expectedUnit) - { - // Currently, no abbreviations are localized for Icelandic, so it should fall back to "en-US" when parsing. - using var _ = new CultureScope("is-IS"); - Assert.True(Scalar.TryParseUnit(abbreviation, out ScalarUnit parsedUnit)); - Assert.Equal(expectedUnit, parsedUnit); - } - - [Theory] - [InlineData("en-US", "", ScalarUnit.Amount)] - public void TryParseUnit_WithCurrentCulture(string culture, string abbreviation, ScalarUnit expectedUnit) - { - using var _ = new CultureScope(culture); - Assert.True(Scalar.TryParseUnit(abbreviation, out ScalarUnit parsedUnit)); - Assert.Equal(expectedUnit, parsedUnit); - } - - [Theory] - [InlineData("en-US", "", ScalarUnit.Amount)] - public void TryParseUnit_WithCulture(string culture, string abbreviation, ScalarUnit expectedUnit) - { - Assert.True(Scalar.TryParseUnit(abbreviation, CultureInfo.GetCultureInfo(culture), out ScalarUnit parsedUnit)); - Assert.Equal(expectedUnit, parsedUnit); - } - - [Theory] - [InlineData("en-US", ScalarUnit.Amount, "")] - public void GetAbbreviationForCulture(string culture, ScalarUnit unit, string expectedAbbreviation) - { - var defaultAbbreviation = Scalar.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); - Assert.Equal(expectedAbbreviation, defaultAbbreviation); - } - - [Fact] - public void GetAbbreviationWithDefaultCulture() - { - Assert.All(Scalar.Units, unit => - { - var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); - - var defaultAbbreviation = Scalar.GetAbbreviation(unit); - - Assert.Equal(expectedAbbreviation, defaultAbbreviation); - }); - } - - [Theory] - [MemberData(nameof(UnitTypes))] - public void ToUnit(ScalarUnit unit) - { - var inBaseUnits = Scalar.From(1.0, Scalar.BaseUnit); - var converted = inBaseUnits.ToUnit(unit); - - var conversionFactor = GetConversionFactor(unit); - AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, converted.Value, conversionFactor.Tolerence); - Assert.Equal(unit, converted.Unit); - } - - [Theory] - [MemberData(nameof(UnitTypes))] - public void ToUnit_WithSameUnits_AreEqual(ScalarUnit unit) - { - var quantity = Scalar.From(3.0, unit); - var toUnitWithSameUnit = quantity.ToUnit(unit); - Assert.Equal(quantity, toUnitWithSameUnit); - } - - [Theory] - [MemberData(nameof(UnitTypes))] - public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ScalarUnit unit) - { - Assert.All(Scalar.Units.Where(u => u != Scalar.BaseUnit), fromUnit => - { - var quantity = Scalar.From(3.0, fromUnit); - var converted = quantity.ToUnit(unit); - Assert.Equal(converted.Unit, unit); - }); - } - - [Theory] - [MemberData(nameof(UnitTypes))] - public virtual void ToUnit_FromDefaultQuantity_ReturnsQuantityWithGivenUnit(ScalarUnit unit) - { - var quantity = default(Scalar); - var converted = quantity.ToUnit(unit); - Assert.Equal(converted.Unit, unit); - } - - [Theory] - [MemberData(nameof(UnitTypes))] - public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ScalarUnit unit) - { - var quantity = Scalar.From(3, Scalar.BaseUnit); - Scalar expectedQuantity = quantity.ToUnit(unit); - Assert.Multiple(() => - { - IQuantity quantityToConvert = quantity; - IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); - Assert.Equal(unit, convertedQuantity.Unit); - }, () => - { - IQuantity quantityToConvert = quantity; - IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); - Assert.Equal(unit, convertedQuantity.Unit); - }); - } - - [Fact] - public void ConversionRoundTrip() - { - Scalar amount = Scalar.FromAmount(1); - AssertEx.EqualTolerance(1, Scalar.FromAmount(amount.Amount).Amount, AmountTolerance); - } - - [Fact] - public void ArithmeticOperators() - { - Scalar v = Scalar.FromAmount(1); - AssertEx.EqualTolerance(-1, -v.Amount, AmountTolerance); - AssertEx.EqualTolerance(2, (Scalar.FromAmount(3)-v).Amount, AmountTolerance); - AssertEx.EqualTolerance(2, (v + v).Amount, AmountTolerance); - AssertEx.EqualTolerance(10, (v*10).Amount, AmountTolerance); - AssertEx.EqualTolerance(10, (10*v).Amount, AmountTolerance); - AssertEx.EqualTolerance(2, (Scalar.FromAmount(10)/5).Amount, AmountTolerance); - AssertEx.EqualTolerance(2, Scalar.FromAmount(10)/Scalar.FromAmount(5), AmountTolerance); - } - - [Fact] - public void ComparisonOperators() - { - Scalar oneAmount = Scalar.FromAmount(1); - Scalar twoAmount = Scalar.FromAmount(2); - - Assert.True(oneAmount < twoAmount); - Assert.True(oneAmount <= twoAmount); - Assert.True(twoAmount > oneAmount); - Assert.True(twoAmount >= oneAmount); - - Assert.False(oneAmount > twoAmount); - Assert.False(oneAmount >= twoAmount); - Assert.False(twoAmount < oneAmount); - Assert.False(twoAmount <= oneAmount); - } - - [Fact] - public void CompareToIsImplemented() - { - Scalar amount = Scalar.FromAmount(1); - Assert.Equal(0, amount.CompareTo(amount)); - Assert.True(amount.CompareTo(Scalar.Zero) > 0); - Assert.True(Scalar.Zero.CompareTo(amount) < 0); - } - - [Fact] - public void CompareToThrowsOnTypeMismatch() - { - Scalar amount = Scalar.FromAmount(1); - Assert.Throws(() => amount.CompareTo(new object())); - } - - [Fact] - public void CompareToThrowsOnNull() - { - Scalar amount = Scalar.FromAmount(1); - Assert.Throws(() => amount.CompareTo(null)); - } - - [Theory] - [InlineData(1, ScalarUnit.Amount, 1, ScalarUnit.Amount, true)] // Same value and unit. - [InlineData(1, ScalarUnit.Amount, 2, ScalarUnit.Amount, false)] // Different value. - [InlineData(2, ScalarUnit.Amount, 1, ScalarUnit.Amount, false)] // Different value and unit. - public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ScalarUnit unitA, double valueB, ScalarUnit unitB, bool expectEqual) - { - var a = new Scalar(valueA, unitA); - var b = new Scalar(valueB, unitB); - - // Operator overloads. - Assert.Equal(expectEqual, a == b); - Assert.Equal(expectEqual, b == a); - Assert.Equal(!expectEqual, a != b); - Assert.Equal(!expectEqual, b != a); - - // IEquatable - Assert.Equal(expectEqual, a.Equals(b)); - Assert.Equal(expectEqual, b.Equals(a)); - - // IEquatable - Assert.Equal(expectEqual, a.Equals((object)b)); - Assert.Equal(expectEqual, b.Equals((object)a)); - } - - [Fact] - public void Equals_Null_ReturnsFalse() - { - var a = Scalar.Zero; - - Assert.False(a.Equals((object)null)); - - // "The result of the expression is always 'false'..." - #pragma warning disable CS8073 - Assert.False(a == null); - Assert.False(null == a); - Assert.True(a != null); - Assert.True(null != a); - #pragma warning restore CS8073 - } - - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() - { - Scalar amount = Scalar.FromAmount(1); - Assert.False(amount.Equals(new object())); - } - - [Fact] - public void EqualsReturnsFalseOnNull() - { - Scalar amount = Scalar.FromAmount(1); - Assert.False(amount.Equals(null)); - } - - [Theory] - [InlineData(1, 2)] - [InlineData(100, 110)] - [InlineData(100, 90)] - public void Equals_WithTolerance(double firstValue, double secondValue) - { - var quantity = Scalar.FromAmount(firstValue); - var otherQuantity = Scalar.FromAmount(secondValue); - Scalar maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; - Assert.True(quantity.Equals(quantity, Scalar.Zero)); - Assert.True(quantity.Equals(quantity, maxTolerance)); - Assert.True(quantity.Equals(otherQuantity, maxTolerance)); - Assert.True(quantity.Equals(otherQuantity, largerTolerance)); - Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); - } - - [Fact] - public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() - { - var quantity = Scalar.FromAmount(1); - var negativeTolerance = Scalar.FromAmount(-1); - Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); - } - - [Fact] - public void HasAtLeastOneAbbreviationSpecified() - { - var units = Enum.GetValues(); - foreach (var unit in units) - { - var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); - } - } - - [Fact] - public void BaseDimensionsShouldNeverBeNull() - { - Assert.False(Scalar.BaseDimensions is null); - } - - [Fact] - public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() - { - using var _ = new CultureScope("en-US"); - Assert.Equal("1", new Scalar(1, ScalarUnit.Amount).ToString()); - } - - [Fact] - public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCultureSinceThereAreNoMappings() - { - // Chose this culture, because we don't currently have any abbreviations mapped for that culture and we expect the en-US to be used as fallback. - var swedishCulture = CultureInfo.GetCultureInfo("sv-SE"); - - Assert.Equal("1", new Scalar(1, ScalarUnit.Amount).ToString(swedishCulture)); - } - - [Fact] - public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() - { - var _ = new CultureScope(CultureInfo.InvariantCulture); - Assert.Equal("0.1", new Scalar(0.123456, ScalarUnit.Amount).ToString("s1")); - Assert.Equal("0.12", new Scalar(0.123456, ScalarUnit.Amount).ToString("s2")); - Assert.Equal("0.123", new Scalar(0.123456, ScalarUnit.Amount).ToString("s3")); - Assert.Equal("0.1235", new Scalar(0.123456, ScalarUnit.Amount).ToString("s4")); - } - - [Fact] - public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixForGivenCulture() - { - var culture = CultureInfo.InvariantCulture; - Assert.Equal("0.1", new Scalar(0.123456, ScalarUnit.Amount).ToString("s1", culture)); - Assert.Equal("0.12", new Scalar(0.123456, ScalarUnit.Amount).ToString("s2", culture)); - Assert.Equal("0.123", new Scalar(0.123456, ScalarUnit.Amount).ToString("s3", culture)); - Assert.Equal("0.1235", new Scalar(0.123456, ScalarUnit.Amount).ToString("s4", culture)); - } - - [Theory] - [InlineData(null)] - [InlineData("en-US")] - public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) - { - var quantity = Scalar.FromAmount(1.0); - CultureInfo formatProvider = cultureName == null - ? null - : CultureInfo.GetCultureInfo(cultureName); - - Assert.Equal(quantity.ToString("G", formatProvider), quantity.ToString(null, formatProvider)); - } - - [Theory] - [InlineData(null)] - [InlineData("g")] - public void ToString_NullProvider_EqualsCurrentCulture(string format) - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); - } - - [Fact] - public void GetHashCode_Equals() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); - } - - [Theory] - [InlineData(1.0)] - [InlineData(-1.0)] - public void NegationOperator_ReturnsQuantity_WithNegatedValue(double value) - { - var quantity = Scalar.FromAmount(value); - Assert.Equal(Scalar.FromAmount(-value), -quantity); - } - } -} diff --git a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs deleted file mode 100644 index abc9a24426..0000000000 --- a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs +++ /dev/null @@ -1,726 +0,0 @@ -//------------------------------------------------------------------------------ -// -// 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. - -using System.Globalization; -using System.Resources; -using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif - -#nullable enable - -// ReSharper disable once CheckNamespace - -namespace UnitsNet -{ - /// - /// - /// A way of representing a number of items. - /// - [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] - public readonly partial struct Scalar : - IArithmeticQuantity, -#if NET7_0_OR_GREATER - IDivisionOperators, - IComparisonOperators, - IParsable, -#endif - IComparable, - IComparable, - IEquatable, - IFormattable - { - /// - /// The numeric value this quantity was constructed with. - /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - [DataMember(Name = "Unit", Order = 2)] - private readonly ScalarUnit? _unit; - - /// - /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. - /// - public sealed class ScalarInfo: QuantityInfo - { - /// - public ScalarInfo(string name, ScalarUnit baseUnit, IEnumerable> unitMappings, Scalar zero, BaseDimensions baseDimensions, - QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) - : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) - { - } - - /// - public ScalarInfo(string name, ScalarUnit baseUnit, IEnumerable> unitMappings, Scalar zero, BaseDimensions baseDimensions) - : this(name, baseUnit, unitMappings, zero, baseDimensions, Scalar.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Scalar", typeof(Scalar).Assembly)) - { - } - - /// - /// Creates a new instance of the class with the default settings for the Scalar quantity. - /// - /// A new instance of the class with the default settings. - public static ScalarInfo CreateDefault() - { - return new ScalarInfo(nameof(Scalar), DefaultBaseUnit, GetDefaultMappings(), new Scalar(0, DefaultBaseUnit), DefaultBaseDimensions); - } - - /// - /// Creates a new instance of the class with the default settings for the Scalar quantity and a callback for customizing the default unit mappings. - /// - /// - /// A callback function for customizing the default unit mappings. - /// - /// - /// A new instance of the class with the default settings. - /// - public static ScalarInfo CreateDefault(Func>, IEnumerable>> customizeUnits) - { - return new ScalarInfo(nameof(Scalar), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Scalar(0, DefaultBaseUnit), DefaultBaseDimensions); - } - - /// - /// The for is . - /// - public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; - - /// - /// The default base unit of Scalar is Amount. All conversions, as defined in the , go via this value. - /// - public static ScalarUnit DefaultBaseUnit { get; } = ScalarUnit.Amount; - - /// - /// Retrieves the default mappings for . - /// - /// An of representing the default unit mappings for Scalar. - public static IEnumerable> GetDefaultMappings() - { - yield return new (ScalarUnit.Amount, "Amount", "Amount", BaseUnits.Undefined); - } - } - - static Scalar() - { - Info = ScalarInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); - } - - /// - /// Creates the quantity with the given numeric value and unit. - /// - /// The numeric value to construct this quantity with. - /// The unit representation to construct this quantity with. - public Scalar(double value, ScalarUnit unit) - { - _value = value; - _unit = unit; - } - - #region Static Properties - - /// - /// The containing the default generated conversion functions for instances. - /// - public static UnitConverter DefaultConversionFunctions { get; } - - /// - public static QuantityInfo Info { get; } - - /// - /// The of this quantity. - /// - public static BaseDimensions BaseDimensions => Info.BaseDimensions; - - /// - /// The base unit of Scalar, which is Amount. All conversions go via this value. - /// - public static ScalarUnit BaseUnit => Info.BaseUnitInfo.Value; - - /// - /// All units of measurement for the Scalar quantity. - /// - public static IReadOnlyCollection Units => Info.Units; - - /// - /// Gets an instance of this quantity with a value of 0 in the base unit Amount. - /// - public static Scalar Zero => Info.Zero; - - #endregion - - #region Properties - - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - - /// - public ScalarUnit Unit => _unit.GetValueOrDefault(BaseUnit); - - /// - public QuantityInfo QuantityInfo => Info; - - #region Explicit implementations - - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - -#if NETSTANDARD2_0 - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - IQuantityInstanceInfo IQuantityOfType.QuantityInfo => Info; - - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - QuantityInfo IQuantity.QuantityInfo => Info; - - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - QuantityInfo IQuantity.QuantityInfo => Info; - - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - Enum IQuantity.Unit => Unit; -#endif - - #endregion - - #endregion - - #region Conversion Properties - - /// - /// Gets a value of this quantity converted into - /// - public double Amount => As(ScalarUnit.Amount); - - #endregion - - #region Static Methods - - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ScalarUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ScalarUnit.Amount, ScalarUnit.Amount, quantity => quantity); - - // Register in unit converter: BaseUnit -> ScalarUnit - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - public static string GetAbbreviation(ScalarUnit unit) - { - return GetAbbreviation(unit, null); - } - - /// - /// Get unit abbreviation string. - /// - /// Unit to get abbreviation for. - /// Unit abbreviation string. - /// Format to use for localization. Defaults to if null. - public static string GetAbbreviation(ScalarUnit unit, IFormatProvider? provider) - { - return UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit, provider); - } - - #endregion - - #region Static Factory Methods - - /// - /// Creates a from . - /// - public static Scalar FromAmount(double value) - { - return new Scalar(value, ScalarUnit.Amount); - } - - /// - /// Dynamically convert from value and unit enum to . - /// - /// Value to convert from. - /// Unit to convert from. - /// Scalar unit value. - public static Scalar From(double value, ScalarUnit fromUnit) - { - return new Scalar(value, fromUnit); - } - - #endregion - - #region Static Parse Methods - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", CultureInfo.GetCultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - public static Scalar Parse(string str) - { - return Parse(str, null); - } - - /// - /// Parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.Parse("5.5 m", CultureInfo.GetCultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// - /// Expected string to have one or two pairs of quantity and unit in the format - /// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in" - /// - /// - /// More than one unit is represented by the specified unit abbreviation. - /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of - /// , and . - /// - /// - /// If anything else goes wrong, typically due to a bug or unhandled case. - /// We wrap exceptions in to allow you to distinguish - /// Units.NET exceptions from other exceptions. - /// - /// Format to use when parsing number and unit. Defaults to if null. - public static Scalar Parse(string str, IFormatProvider? provider) - { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// - /// Length.Parse("5.5 m", CultureInfo.GetCultureInfo("en-US")); - /// - public static bool TryParse([NotNullWhen(true)]string? str, out Scalar result) - { - return TryParse(str, null, out result); - } - - /// - /// Try to parse a string with one or two quantities of the format "<quantity> <unit>". - /// - /// String to parse. Typically in the form: {number} {unit} - /// Resulting unit quantity if successful. - /// True if successful, otherwise false. - /// - /// Length.Parse("5.5 m", CultureInfo.GetCultureInfo("en-US")); - /// - /// Format to use when parsing number and unit. Defaults to if null. - public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Scalar result) - { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// - /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ScalarUnit ParseUnit(string str) - { - return ParseUnit(str, null); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. - /// - /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); - /// - /// The value of 'str' cannot be null. - /// Error parsing string. - public static ScalarUnit ParseUnit(string str, IFormatProvider? provider) - { - return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; - } - - /// - public static bool TryParseUnit([NotNullWhen(true)]string? str, out ScalarUnit unit) - { - return TryParseUnit(str, null, out unit); - } - - /// - /// Parse a unit string. - /// - /// String to parse. Typically in the form: {number} {unit} - /// The parsed unit if successful. - /// True if successful, otherwise false. - /// - /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); - /// - /// Format to use when parsing number and unit. Defaults to if null. - public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ScalarUnit unit) - { - return UnitParser.Default.TryParse(str, Info, provider, out unit); - } - - #endregion - - #region Arithmetic Operators - - /// Negate the value. - public static Scalar operator -(Scalar right) - { - return new Scalar(-right.Value, right.Unit); - } - - /// Get from adding two . - public static Scalar operator +(Scalar left, Scalar right) - { - return new Scalar(left.Value + right.ToUnit(left.Unit).Value, left.Unit); - } - - /// Get from subtracting two . - public static Scalar operator -(Scalar left, Scalar right) - { - return new Scalar(left.Value - right.ToUnit(left.Unit).Value, left.Unit); - } - - /// Get from multiplying value and . - public static Scalar operator *(double left, Scalar right) - { - return new Scalar(left * right.Value, right.Unit); - } - - /// Get from multiplying value and . - public static Scalar operator *(Scalar left, double right) - { - return new Scalar(left.Value * right, left.Unit); - } - - /// Get from dividing by value. - public static Scalar operator /(Scalar left, double right) - { - return new Scalar(left.Value / right, left.Unit); - } - - /// Get ratio value from dividing by . - public static double operator /(Scalar left, Scalar right) - { - return left.Amount / right.Amount; - } - - #endregion - - #region Equality / IComparable - - /// Returns true if less or equal to. - public static bool operator <=(Scalar left, Scalar right) - { - return left.Value <= right.ToUnit(left.Unit).Value; - } - - /// Returns true if greater than or equal to. - public static bool operator >=(Scalar left, Scalar right) - { - return left.Value >= right.ToUnit(left.Unit).Value; - } - - /// Returns true if less than. - public static bool operator <(Scalar left, Scalar right) - { - return left.Value < right.ToUnit(left.Unit).Value; - } - - /// Returns true if greater than. - public static bool operator >(Scalar left, Scalar right) - { - return left.Value > right.ToUnit(left.Unit).Value; - } - - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Scalar other, Scalar tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] - public static bool operator ==(Scalar left, Scalar right) - { - return left.Equals(right); - } - - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Scalar other, Scalar tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] - public static bool operator !=(Scalar left, Scalar right) - { - return !(left == right); - } - - /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Scalar other, Scalar tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] - public override bool Equals(object? obj) - { - if (obj is null || !(obj is Scalar otherQuantity)) - return false; - - return Equals(otherQuantity); - } - - /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Scalar other, Scalar tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] - public bool Equals(Scalar other) - { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); - } - - #pragma warning restore CS0809 - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Scalar. - public override int GetHashCode() - { - return Comparison.GetHashCode(Unit, Value); - } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. - /// An object to compare with this instance. - /// - /// is not the same type as this instance. - /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// - public int CompareTo(object? obj) - { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Scalar otherQuantity)) throw new ArgumentException("Expected type Scalar.", nameof(obj)); - - return CompareTo(otherQuantity); - } - - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. - /// A quantity to compare with this instance. - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// - public int CompareTo(Scalar other) - { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - #endregion - - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ScalarUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - /// Converts this Scalar to another Scalar with the unit representation . - /// - /// The unit to convert to. - /// A Scalar with the specified unit. - public Scalar ToUnit(ScalarUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Scalar with the specified unit. - public Scalar ToUnit(ScalarUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Scalar), Unit, typeof(Scalar), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Scalar)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ScalarUnit unit, [NotNullWhen(true)] out Scalar? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Scalar? convertedOrNull = (Unit, unit) switch - { - // ScalarUnit -> BaseUnit - - // BaseUnit -> ScalarUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ScalarUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ScalarUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(ScalarUnit unit) => ToUnit(unit); - - #endregion - - #endregion - - #region ToString Methods - - /// - /// Gets the default string representation of value and unit. - /// - /// String representation. - public override string ToString() - { - return ToString(null, null); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. - /// - public string ToString(string? format, IFormatProvider? provider) - { - return QuantityFormatter.Default.Format(this, format, provider); - } - - #endregion - - } -} diff --git a/UnitsNet/GeneratedCode/Quantity.g.cs b/UnitsNet/GeneratedCode/Quantity.g.cs index c7a7c3af9c..58044a9ad4 100644 --- a/UnitsNet/GeneratedCode/Quantity.g.cs +++ b/UnitsNet/GeneratedCode/Quantity.g.cs @@ -138,7 +138,6 @@ internal static class DefaultProvider RotationalSpeed.Info, RotationalStiffness.Info, RotationalStiffnessPerLength.Info, - Scalar.Info, SolidAngle.Info, SpecificEnergy.Info, SpecificEntropy.Info, @@ -270,7 +269,6 @@ internal static void RegisterUnitConversions(UnitConverter unitConverter) RotationalSpeed.RegisterDefaultConversions(unitConverter); RotationalStiffness.RegisterDefaultConversions(unitConverter); RotationalStiffnessPerLength.RegisterDefaultConversions(unitConverter); - Scalar.RegisterDefaultConversions(unitConverter); SolidAngle.RegisterDefaultConversions(unitConverter); SpecificEnergy.RegisterDefaultConversions(unitConverter); SpecificEntropy.RegisterDefaultConversions(unitConverter); diff --git a/UnitsNet/GeneratedCode/Resources/Scalar.restext b/UnitsNet/GeneratedCode/Resources/Scalar.restext deleted file mode 100644 index 8a5376da0d..0000000000 --- a/UnitsNet/GeneratedCode/Resources/Scalar.restext +++ /dev/null @@ -1 +0,0 @@ -Amount= diff --git a/UnitsNet/GeneratedCode/Units/ScalarUnit.g.cs b/UnitsNet/GeneratedCode/Units/ScalarUnit.g.cs deleted file mode 100644 index c8be591b38..0000000000 --- a/UnitsNet/GeneratedCode/Units/ScalarUnit.g.cs +++ /dev/null @@ -1,32 +0,0 @@ -//------------------------------------------------------------------------------ -// -// 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.Units -{ - // Disable missing XML comment warnings for the generated unit enums. - #pragma warning disable 1591 - - public enum ScalarUnit - { - Amount = 1, - } - - #pragma warning restore 1591 -}