From fa85785e5cfa35a571053a067b9bb6bba1b3cc67 Mon Sep 17 00:00:00 2001 From: Tobias Schulte Date: Fri, 10 Apr 2026 12:08:02 +0200 Subject: [PATCH] =?UTF-8?q?add=20flatness=20quantity=20with=20units=20I-Un?= =?UTF-8?q?it=20and=20=C2=B5m/m?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Common/UnitDefinitions/Flatness.json | 31 + Common/UnitEnumValues.g.json | 4 + .../GeneratedCode/Flatness/Flatness.nfproj | 42 + .../UnitsNet.NanoFramework.Flatness.nuspec | 26 + .../GeneratedCode/Flatness/packages.config | 4 + .../GeneratedCode/Quantities/Flatness.g.cs | 169 ++++ .../GeneratedCode/Units/FlatnessUnit.g.cs | 33 + .../GeneratedCode/UnitsNet.nanoFramework.sln | 8 + .../NumberToFlatnessExtensionsTest.g.cs | 36 + .../NumberToFlatnessExtensions.g.cs | 63 ++ .../NumberToFlatnessExtensionsTest.g.cs | 36 + .../NumberToFlatnessExtensions.g.cs | 58 ++ UnitsNet.Tests/CustomCode/FlatnessTests.cs | 29 + .../GeneratedCode/IQuantityTests.g.cs | 2 + .../TestsBase/FlatnessTestsBase.g.cs | 625 +++++++++++++++ .../GeneratedCode/Quantities/Flatness.g.cs | 744 ++++++++++++++++++ .../GeneratedCode/Resources/Flatness.restext | 2 + .../GeneratedCode/Units/FlatnessUnit.g.cs | 33 + 18 files changed, 1945 insertions(+) create mode 100644 Common/UnitDefinitions/Flatness.json create mode 100644 UnitsNet.NanoFramework/GeneratedCode/Flatness/Flatness.nfproj create mode 100644 UnitsNet.NanoFramework/GeneratedCode/Flatness/UnitsNet.NanoFramework.Flatness.nuspec create mode 100644 UnitsNet.NanoFramework/GeneratedCode/Flatness/packages.config create mode 100644 UnitsNet.NanoFramework/GeneratedCode/Quantities/Flatness.g.cs create mode 100644 UnitsNet.NanoFramework/GeneratedCode/Units/FlatnessUnit.g.cs create mode 100644 UnitsNet.NumberExtensions.CS14.Tests/GeneratedCode/NumberToFlatnessExtensionsTest.g.cs create mode 100644 UnitsNet.NumberExtensions.CS14/GeneratedCode/NumberToFlatnessExtensions.g.cs create mode 100644 UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToFlatnessExtensionsTest.g.cs create mode 100644 UnitsNet.NumberExtensions/GeneratedCode/NumberToFlatnessExtensions.g.cs create mode 100644 UnitsNet.Tests/CustomCode/FlatnessTests.cs create mode 100644 UnitsNet.Tests/GeneratedCode/TestsBase/FlatnessTestsBase.g.cs create mode 100644 UnitsNet/GeneratedCode/Quantities/Flatness.g.cs create mode 100644 UnitsNet/GeneratedCode/Resources/Flatness.restext create mode 100644 UnitsNet/GeneratedCode/Units/FlatnessUnit.g.cs diff --git a/Common/UnitDefinitions/Flatness.json b/Common/UnitDefinitions/Flatness.json new file mode 100644 index 0000000000..133ad4590c --- /dev/null +++ b/Common/UnitDefinitions/Flatness.json @@ -0,0 +1,31 @@ +{ + "Name": "Flatness", + "BaseUnit": "IUnit", + "XmlDocSummary": "Flatness is a measurement for the deviation of a surface from a perfectly flat surface.", + "Units": [ + { + "SingularName": "IUnit", + "PluralName": "IUnits", + "FromUnitToBaseFunc": "{x}", + "FromBaseToUnitFunc": "{x}", + "Localization": [ + { + "Culture": "en-US", + "Abbreviations": [ "I-Units" ] + } + ] + }, + { + "SingularName": "MicrometerPerMeter", + "PluralName": "MicrometersPerMeter", + "FromUnitToBaseFunc": "{x} / 1e1", + "FromBaseToUnitFunc": "{x} * 1e1", + "Localization": [ + { + "Culture": "en-US", + "Abbreviations": [ "µm/m" ] + } + ] + } + ] +} diff --git a/Common/UnitEnumValues.g.json b/Common/UnitEnumValues.g.json index 3ebdc3d87d..65f8a53196 100644 --- a/Common/UnitEnumValues.g.json +++ b/Common/UnitEnumValues.g.json @@ -2018,5 +2018,9 @@ "SquareMeterKelvinPerKilowatt": 5, "SquareMeterKelvinPerWatt": 4, "SquareMillimeterKelvinPerWatt": 13 + }, + "Flatness": { + "IUnit": 2, + "MicrometerPerMeter": 4 } } diff --git a/UnitsNet.NanoFramework/GeneratedCode/Flatness/Flatness.nfproj b/UnitsNet.NanoFramework/GeneratedCode/Flatness/Flatness.nfproj new file mode 100644 index 0000000000..7a5d51fe41 --- /dev/null +++ b/UnitsNet.NanoFramework/GeneratedCode/Flatness/Flatness.nfproj @@ -0,0 +1,42 @@ + + + + $(MSBuildExtensionsPath)\nanoFramework\v1.0\ + + + + Debug + AnyCPU + {11A8DD76-328B-46DF-9F39-F559912D0360};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + {7953bc3b-7afc-6983-c7f3-b8d65f6e1647} + Library + Properties + 512 + UnitsNet + UnitsNet.Flatness + v1.0 + bin\$(Configuration)\$(AssemblyName).xml + + + + + + + + + + ..\packages\nanoFramework.CoreLibrary.1.15.5\lib\mscorlib.dll + True + True + + + + + + + + + + + + diff --git a/UnitsNet.NanoFramework/GeneratedCode/Flatness/UnitsNet.NanoFramework.Flatness.nuspec b/UnitsNet.NanoFramework/GeneratedCode/Flatness/UnitsNet.NanoFramework.Flatness.nuspec new file mode 100644 index 0000000000..4b517b6fc7 --- /dev/null +++ b/UnitsNet.NanoFramework/GeneratedCode/Flatness/UnitsNet.NanoFramework.Flatness.nuspec @@ -0,0 +1,26 @@ + + + + UnitsNet.nanoFramework.Flatness + 6.0.0-pre019 + Units.NET Flatness - nanoFramework + Andreas Gullberg Larsen,nanoframework + UnitsNet + MIT-0 + https://github.com/angularsen/UnitsNet + false + Adds Flatness units for Units.NET on .NET nanoFramework. For .NET or .NET Core, use UnitsNet instead. + https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png + + + Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). + en-US + nanoframework flatness unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable + + + + + + + + diff --git a/UnitsNet.NanoFramework/GeneratedCode/Flatness/packages.config b/UnitsNet.NanoFramework/GeneratedCode/Flatness/packages.config new file mode 100644 index 0000000000..313a8dccdf --- /dev/null +++ b/UnitsNet.NanoFramework/GeneratedCode/Flatness/packages.config @@ -0,0 +1,4 @@ + + + + diff --git a/UnitsNet.NanoFramework/GeneratedCode/Quantities/Flatness.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Flatness.g.cs new file mode 100644 index 0000000000..4261914c67 --- /dev/null +++ b/UnitsNet.NanoFramework/GeneratedCode/Quantities/Flatness.g.cs @@ -0,0 +1,169 @@ +//------------------------------------------------------------------------------ +// +// 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 UnitsNet.Units; + +namespace UnitsNet +{ + /// + /// + /// Flatness is a measurement for the deviation of a surface from a perfectly flat surface. + /// + public struct Flatness + { + /// + /// The numeric value this quantity was constructed with. + /// + private readonly double _value; + + /// + /// The unit this quantity was constructed with. + /// + private readonly FlatnessUnit _unit; + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + public FlatnessUnit Unit => _unit; + + /// + /// 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 Flatness(double value, FlatnessUnit unit) + { + _value = value; + _unit = unit; + } + + /// + /// The base unit of Flatness, which is Second. All conversions go via this value. + /// + public static FlatnessUnit BaseUnit { get; } = FlatnessUnit.IUnit; + + /// + /// Represents the largest possible value of Flatness. + /// + public static Flatness MaxValue { get; } = new Flatness(double.MaxValue, BaseUnit); + + /// + /// Represents the smallest possible value of Flatness. + /// + public static Flatness MinValue { get; } = new Flatness(double.MinValue, BaseUnit); + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit Second. + /// + public static Flatness Zero { get; } = new Flatness(0, BaseUnit); + #region Conversion Properties + + /// + /// Gets a value of this quantity converted into + /// + public double IUnits => As(FlatnessUnit.IUnit); + + /// + /// Gets a value of this quantity converted into + /// + public double MicrometersPerMeter => As(FlatnessUnit.MicrometerPerMeter); + + #endregion + + #region Static Factory Methods + + /// + /// Creates a from . + /// + public static Flatness FromIUnits(double iunits) => new Flatness(iunits, FlatnessUnit.IUnit); + + /// + /// Creates a from . + /// + public static Flatness FromMicrometersPerMeter(double micrometerspermeter) => new Flatness(micrometerspermeter, FlatnessUnit.MicrometerPerMeter); + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Flatness unit value. + public static Flatness From(double value, FlatnessUnit fromUnit) + { + return new Flatness(value, fromUnit); + } + + #endregion + + #region Conversion Methods + + /// + /// Convert to the unit representation . + /// + /// Value converted to the specified unit. + public double As(FlatnessUnit unit) => GetValueAs(unit); + + /// + /// Converts this Flatness to another Flatness with the unit representation . + /// + /// A Flatness with the specified unit. + public Flatness ToUnit(FlatnessUnit unit) + { + var convertedValue = GetValueAs(unit); + return new Flatness(convertedValue, unit); + } + + /// + /// Converts the current value + unit to the base unit. + /// This is typically the first step in converting from one unit to another. + /// + /// The value in the base unit representation. + private double GetValueInBaseUnit() + { + return Unit switch + { + FlatnessUnit.IUnit => _value, + FlatnessUnit.MicrometerPerMeter => _value / 1e1, + _ => throw new NotImplementedException($"Can't convert {Unit} to base units.") + }; + } + + private double GetValueAs(FlatnessUnit unit) + { + if (Unit == unit) + return _value; + + var baseUnitValue = GetValueInBaseUnit(); + + return unit switch + { + FlatnessUnit.IUnit => baseUnitValue, + FlatnessUnit.MicrometerPerMeter => baseUnitValue * 1e1, + _ => throw new NotImplementedException($"Can't convert {Unit} to {unit}.") + }; + } + + #endregion + } +} + diff --git a/UnitsNet.NanoFramework/GeneratedCode/Units/FlatnessUnit.g.cs b/UnitsNet.NanoFramework/GeneratedCode/Units/FlatnessUnit.g.cs new file mode 100644 index 0000000000..21a93e226a --- /dev/null +++ b/UnitsNet.NanoFramework/GeneratedCode/Units/FlatnessUnit.g.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// 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 FlatnessUnit + { + IUnit = 2, + MicrometerPerMeter = 4, + } + + #pragma warning restore 1591 +} diff --git a/UnitsNet.NanoFramework/GeneratedCode/UnitsNet.nanoFramework.sln b/UnitsNet.NanoFramework/GeneratedCode/UnitsNet.nanoFramework.sln index f2d98d63c4..4a2265f805 100644 --- a/UnitsNet.NanoFramework/GeneratedCode/UnitsNet.nanoFramework.sln +++ b/UnitsNet.NanoFramework/GeneratedCode/UnitsNet.nanoFramework.sln @@ -86,6 +86,8 @@ Project("{d608a2b1-6ead-4383-a205-ad1ce69d9ef7}") = "EnergyDensity", "EnergyDens EndProject Project("{d608a2b1-6ead-4383-a205-ad1ce69d9ef7}") = "Entropy", "Entropy\Entropy.nfproj", "{816884bb-a5f6-5c07-967b-bb8f21d724b7}" EndProject +Project("{d608a2b1-6ead-4383-a205-ad1ce69d9ef7}") = "Flatness", "Flatness\Flatness.nfproj", "{7953bc3b-7afc-6983-c7f3-b8d65f6e1647}" +EndProject Project("{d608a2b1-6ead-4383-a205-ad1ce69d9ef7}") = "FluidResistance", "FluidResistance\FluidResistance.nfproj", "{d19281dc-72f6-62a9-18d5-b845d6fd8d99}" EndProject Project("{d608a2b1-6ead-4383-a205-ad1ce69d9ef7}") = "Force", "Force\Force.nfproj", "{5517dacf-b1ff-6515-e5b6-b5081f92f407}" @@ -516,6 +518,12 @@ Global {816884bb-a5f6-5c07-967b-bb8f21d724b7}.Release|Any CPU.ActiveCfg = Release|Any CPU {816884bb-a5f6-5c07-967b-bb8f21d724b7}.Release|Any CPU.Build.0 = Release|Any CPU {816884bb-a5f6-5c07-967b-bb8f21d724b7}.Release|Any CPU.Deploy.0 = Release|Any CPU +{7953bc3b-7afc-6983-c7f3-b8d65f6e1647}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{7953bc3b-7afc-6983-c7f3-b8d65f6e1647}.Debug|Any CPU.Build.0 = Debug|Any CPU +{7953bc3b-7afc-6983-c7f3-b8d65f6e1647}.Debug|Any CPU.Deploy.0 = Debug|Any CPU +{7953bc3b-7afc-6983-c7f3-b8d65f6e1647}.Release|Any CPU.ActiveCfg = Release|Any CPU +{7953bc3b-7afc-6983-c7f3-b8d65f6e1647}.Release|Any CPU.Build.0 = Release|Any CPU +{7953bc3b-7afc-6983-c7f3-b8d65f6e1647}.Release|Any CPU.Deploy.0 = Release|Any CPU {d19281dc-72f6-62a9-18d5-b845d6fd8d99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {d19281dc-72f6-62a9-18d5-b845d6fd8d99}.Debug|Any CPU.Build.0 = Debug|Any CPU {d19281dc-72f6-62a9-18d5-b845d6fd8d99}.Debug|Any CPU.Deploy.0 = Debug|Any CPU diff --git a/UnitsNet.NumberExtensions.CS14.Tests/GeneratedCode/NumberToFlatnessExtensionsTest.g.cs b/UnitsNet.NumberExtensions.CS14.Tests/GeneratedCode/NumberToFlatnessExtensionsTest.g.cs new file mode 100644 index 0000000000..b9a55ee8ed --- /dev/null +++ b/UnitsNet.NumberExtensions.CS14.Tests/GeneratedCode/NumberToFlatnessExtensionsTest.g.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// +// 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.NumberToFlatness; +using Xunit; + +namespace UnitsNet.Tests +{ + public class NumberToFlatnessExtensionsTests + { + [Fact] + public void NumberToIUnitsTest() => + Assert.Equal(Flatness.FromIUnits(2), 2.IUnits); + + [Fact] + public void NumberToMicrometersPerMeterTest() => + Assert.Equal(Flatness.FromMicrometersPerMeter(2), 2.MicrometersPerMeter); + + } +} diff --git a/UnitsNet.NumberExtensions.CS14/GeneratedCode/NumberToFlatnessExtensions.g.cs b/UnitsNet.NumberExtensions.CS14/GeneratedCode/NumberToFlatnessExtensions.g.cs new file mode 100644 index 0000000000..45750aa574 --- /dev/null +++ b/UnitsNet.NumberExtensions.CS14/GeneratedCode/NumberToFlatnessExtensions.g.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// 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.NumberToFlatness +{ + /// + /// A number to Flatness Extensions + /// + public static class NumberToFlatnessExtensions + { +#pragma warning disable CS1591 + extension(T value) +#pragma warning restore CS1591 + where T : notnull +#if NET7_0_OR_GREATER + , INumber +#else + , IConvertible +#endif + { + /// + public Flatness IUnits +#if NET7_0_OR_GREATER + => Flatness.FromIUnits(double.CreateChecked(value)); +#else + => Flatness.FromIUnits(value.ToDouble(null)); +#endif + + /// + public Flatness MicrometersPerMeter +#if NET7_0_OR_GREATER + => Flatness.FromMicrometersPerMeter(double.CreateChecked(value)); +#else + => Flatness.FromMicrometersPerMeter(value.ToDouble(null)); +#endif + + } + } +} diff --git a/UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToFlatnessExtensionsTest.g.cs b/UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToFlatnessExtensionsTest.g.cs new file mode 100644 index 0000000000..e938ccae71 --- /dev/null +++ b/UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToFlatnessExtensionsTest.g.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// +// 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.NumberToFlatness; +using Xunit; + +namespace UnitsNet.Tests +{ + public class NumberToFlatnessExtensionsTests + { + [Fact] + public void NumberToIUnitsTest() => + Assert.Equal(Flatness.FromIUnits(2), 2.IUnits()); + + [Fact] + public void NumberToMicrometersPerMeterTest() => + Assert.Equal(Flatness.FromMicrometersPerMeter(2), 2.MicrometersPerMeter()); + + } +} diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToFlatnessExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToFlatnessExtensions.g.cs new file mode 100644 index 0000000000..6b1557a7ac --- /dev/null +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToFlatnessExtensions.g.cs @@ -0,0 +1,58 @@ +//------------------------------------------------------------------------------ +// +// 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.NumberToFlatness +{ + /// + /// A number to Flatness Extensions + /// + public static class NumberToFlatnessExtensions + { + /// + public static Flatness IUnits(this T value) + where T : notnull +#if NET7_0_OR_GREATER + , INumber + => Flatness.FromIUnits(double.CreateChecked(value)); +#else + , IConvertible + => Flatness.FromIUnits(value.ToDouble(null)); +#endif + + /// + public static Flatness MicrometersPerMeter(this T value) + where T : notnull +#if NET7_0_OR_GREATER + , INumber + => Flatness.FromMicrometersPerMeter(double.CreateChecked(value)); +#else + , IConvertible + => Flatness.FromMicrometersPerMeter(value.ToDouble(null)); +#endif + + } +} diff --git a/UnitsNet.Tests/CustomCode/FlatnessTests.cs b/UnitsNet.Tests/CustomCode/FlatnessTests.cs new file mode 100644 index 0000000000..bee5896a87 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/FlatnessTests.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// 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; + +namespace UnitsNet.Tests.CustomCode +{ + public class FlatnessTests : FlatnessTestsBase + { + protected override double IUnitsInOneIUnit => 1; + protected override double MicrometersPerMeterInOneIUnit => 10; + } +} diff --git a/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs b/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs index 9dfabd182a..49bfe48dcb 100644 --- a/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs +++ b/UnitsNet.Tests/GeneratedCode/IQuantityTests.g.cs @@ -76,6 +76,7 @@ void Assertion(int expectedValue, Enum expectedUnit, IQuantity quantity) Assertion(3, EnergyUnit.WattHour, Quantity.From(3, EnergyUnit.WattHour)); Assertion(3, EnergyDensityUnit.WattHourPerCubicMeter, Quantity.From(3, EnergyDensityUnit.WattHourPerCubicMeter)); Assertion(3, EntropyUnit.MegajoulePerKelvin, Quantity.From(3, EntropyUnit.MegajoulePerKelvin)); + Assertion(3, FlatnessUnit.MicrometerPerMeter, Quantity.From(3, FlatnessUnit.MicrometerPerMeter)); Assertion(3, FluidResistanceUnit.WoodUnit, Quantity.From(3, FluidResistanceUnit.WoodUnit)); Assertion(3, ForceUnit.TonneForce, Quantity.From(3, ForceUnit.TonneForce)); Assertion(3, ForceChangeRateUnit.PoundForcePerSecond, Quantity.From(3, ForceChangeRateUnit.PoundForcePerSecond)); @@ -211,6 +212,7 @@ public void QuantityInfo_IsSameAsStaticInfoProperty() Assertion(Energy.Info, Energy.Zero); Assertion(EnergyDensity.Info, EnergyDensity.Zero); Assertion(Entropy.Info, Entropy.Zero); + Assertion(Flatness.Info, Flatness.Zero); Assertion(FluidResistance.Info, FluidResistance.Zero); Assertion(Force.Info, Force.Zero); Assertion(ForceChangeRate.Info, ForceChangeRate.Zero); diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/FlatnessTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/FlatnessTestsBase.g.cs new file mode 100644 index 0000000000..f339f4ecc6 --- /dev/null +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FlatnessTestsBase.g.cs @@ -0,0 +1,625 @@ +//------------------------------------------------------------------------------ +// +// 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 Flatness. + /// +// ReSharper disable once PartialTypeWithSinglePart + public abstract partial class FlatnessTestsBase : QuantityTestsBase + { + protected abstract double IUnitsInOneIUnit { get; } + protected abstract double MicrometersPerMeterInOneIUnit { get; } + +// ReSharper disable VirtualMemberNeverOverriden.Global + protected virtual double IUnitsTolerance { get { return 1e-5; } } + protected virtual double MicrometersPerMeterTolerance { get { return 1e-5; } } +// ReSharper restore VirtualMemberNeverOverriden.Global + + protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor(FlatnessUnit unit) + { + return unit switch + { + FlatnessUnit.IUnit => (IUnitsInOneIUnit, IUnitsTolerance), + FlatnessUnit.MicrometerPerMeter => (MicrometersPerMeterInOneIUnit, MicrometersPerMeterTolerance), + _ => throw new NotSupportedException() + }; + } + + public static IEnumerable UnitTypes = new List + { + new object[] { FlatnessUnit.IUnit }, + new object[] { FlatnessUnit.MicrometerPerMeter }, + }; + + [Fact] + public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit() + { + var quantity = new Flatness(); + Assert.Equal(0, quantity.Value); + Assert.Equal(FlatnessUnit.IUnit, quantity.Unit); + } + + [Fact] + public void Ctor_WithInfinityValue_DoNotThrowsArgumentException() + { + var exception1 = Record.Exception(() => new Flatness(double.PositiveInfinity, FlatnessUnit.IUnit)); + var exception2 = Record.Exception(() => new Flatness(double.NegativeInfinity, FlatnessUnit.IUnit)); + + Assert.Null(exception1); + Assert.Null(exception2); + } + + [Fact] + public void Ctor_WithNaNValue_DoNotThrowsArgumentException() + { + var exception = Record.Exception(() => new Flatness(double.NaN, FlatnessUnit.IUnit)); + + Assert.Null(exception); + } + + [Fact] + public void Flatness_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() + { + FlatnessUnit[] unitsOrderedByName = EnumHelper.GetValues().OrderBy(x => x.ToString(), StringComparer.OrdinalIgnoreCase).ToArray(); + var quantity = new Flatness(1, FlatnessUnit.IUnit); + + QuantityInfo quantityInfo = quantity.QuantityInfo; + + Assert.Equal("Flatness", quantityInfo.Name); + Assert.Equal(Flatness.Zero, quantityInfo.Zero); + Assert.Equal(Flatness.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Flatness.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void IUnitToFlatnessUnits() + { + Flatness iunit = Flatness.FromIUnits(1); + AssertEx.EqualTolerance(IUnitsInOneIUnit, iunit.IUnits, IUnitsTolerance); + AssertEx.EqualTolerance(MicrometersPerMeterInOneIUnit, iunit.MicrometersPerMeter, MicrometersPerMeterTolerance); + } + + [Fact] + public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() + { + Assert.All(EnumHelper.GetValues(), unit => + { + var quantity = Flatness.From(1, unit); + Assert.Equal(1, quantity.Value); + Assert.Equal(unit, quantity.Unit); + }); + } + + [Fact] + public void FromIUnits_WithInfinityValue_DoNotThrowsArgumentException() + { + var exception1 = Record.Exception(() => Flatness.FromIUnits(double.PositiveInfinity)); + var exception2 = Record.Exception(() => Flatness.FromIUnits(double.NegativeInfinity)); + + Assert.Null(exception1); + Assert.Null(exception2); + } + + [Fact] + public void FromIUnits_WithNanValue_DoNotThrowsArgumentException() + { + var exception = Record.Exception(() => Flatness.FromIUnits(double.NaN)); + + Assert.Null(exception); + } + + [Fact] + public void As() + { + var iunit = Flatness.FromIUnits(1); + AssertEx.EqualTolerance(IUnitsInOneIUnit, iunit.As(FlatnessUnit.IUnit), IUnitsTolerance); + AssertEx.EqualTolerance(MicrometersPerMeterInOneIUnit, iunit.As(FlatnessUnit.MicrometerPerMeter), MicrometersPerMeterTolerance); + } + + [Fact] + public void As_UnitSystem_ReturnsValueInDimensionlessUnit() + { + var quantity = new Flatness(value: 1, unit: FlatnessUnit.IUnit); + + var convertedValue = quantity.As(UnitSystem.SI); + + Assert.Equal(quantity.Value, convertedValue); + } + + [Fact] + public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + var quantity = new Flatness(value: 1, unit: Flatness.BaseUnit); + UnitSystem nullUnitSystem = null!; + Assert.Throws(() => quantity.As(nullUnitSystem)); + } + + [Fact] + public void ToUnit_UnitSystem_ReturnsValueInDimensionlessUnit() + { + var quantity = new Flatness(value: 1, unit: FlatnessUnit.IUnit); + + Flatness convertedQuantity = quantity.ToUnit(UnitSystem.SI); + + Assert.Equal(FlatnessUnit.IUnit, convertedQuantity.Unit); + Assert.Equal(quantity.Value, convertedQuantity.Value); + } + + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + UnitSystem nullUnitSystem = null!; + Assert.Multiple(() => + { + var quantity = new Flatness(value: 1, unit: Flatness.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => + { + IQuantity quantity = new Flatness(value: 1, unit: Flatness.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => + { + IQuantity quantity = new Flatness(value: 1, unit: Flatness.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }); + } + + [Theory] + [InlineData("en-US", "4.2 I-Units", FlatnessUnit.IUnit, 4.2)] + [InlineData("en-US", "4.2 µm/m", FlatnessUnit.MicrometerPerMeter, 4.2)] + public void Parse(string culture, string quantityString, FlatnessUnit expectedUnit, double expectedValue) + { + using var _ = new CultureScope(culture); + var parsed = Flatness.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } + + [Theory] + [InlineData("en-US", "4.2 I-Units", FlatnessUnit.IUnit, 4.2)] + [InlineData("en-US", "4.2 µm/m", FlatnessUnit.MicrometerPerMeter, 4.2)] + public void TryParse(string culture, string quantityString, FlatnessUnit expectedUnit, double expectedValue) + { + using var _ = new CultureScope(culture); + Assert.True(Flatness.TryParse(quantityString, out Flatness parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } + + [Theory] + [InlineData("I-Units", FlatnessUnit.IUnit)] + [InlineData("µm/m", FlatnessUnit.MicrometerPerMeter)] + public void ParseUnit_WithUsEnglishCurrentCulture(string abbreviation, FlatnessUnit expectedUnit) + { + // Fallback culture "en-US" is always localized + using var _ = new CultureScope("en-US"); + FlatnessUnit parsedUnit = Flatness.ParseUnit(abbreviation); + Assert.Equal(expectedUnit, parsedUnit); + } + + [Theory] + [InlineData("I-Units", FlatnessUnit.IUnit)] + [InlineData("µm/m", FlatnessUnit.MicrometerPerMeter)] + public void ParseUnit_WithUnsupportedCurrentCulture_FallsBackToUsEnglish(string abbreviation, FlatnessUnit expectedUnit) + { + // Currently, no abbreviations are localized for Icelandic, so it should fall back to "en-US" when parsing. + using var _ = new CultureScope("is-IS"); + FlatnessUnit parsedUnit = Flatness.ParseUnit(abbreviation); + Assert.Equal(expectedUnit, parsedUnit); + } + + [Theory] + [InlineData("en-US", "I-Units", FlatnessUnit.IUnit)] + [InlineData("en-US", "µm/m", FlatnessUnit.MicrometerPerMeter)] + public void ParseUnit_WithCurrentCulture(string culture, string abbreviation, FlatnessUnit expectedUnit) + { + using var _ = new CultureScope(culture); + FlatnessUnit parsedUnit = Flatness.ParseUnit(abbreviation); + Assert.Equal(expectedUnit, parsedUnit); + } + + [Theory] + [InlineData("en-US", "I-Units", FlatnessUnit.IUnit)] + [InlineData("en-US", "µm/m", FlatnessUnit.MicrometerPerMeter)] + public void ParseUnit_WithCulture(string culture, string abbreviation, FlatnessUnit expectedUnit) + { + FlatnessUnit parsedUnit = Flatness.ParseUnit(abbreviation, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedUnit, parsedUnit); + } + + [Theory] + [InlineData("I-Units", FlatnessUnit.IUnit)] + [InlineData("µm/m", FlatnessUnit.MicrometerPerMeter)] + public void TryParseUnit_WithUsEnglishCurrentCulture(string abbreviation, FlatnessUnit expectedUnit) + { + // Fallback culture "en-US" is always localized + using var _ = new CultureScope("en-US"); + Assert.True(Flatness.TryParseUnit(abbreviation, out FlatnessUnit parsedUnit)); + Assert.Equal(expectedUnit, parsedUnit); + } + + [Theory] + [InlineData("I-Units", FlatnessUnit.IUnit)] + [InlineData("µm/m", FlatnessUnit.MicrometerPerMeter)] + public void TryParseUnit_WithUnsupportedCurrentCulture_FallsBackToUsEnglish(string abbreviation, FlatnessUnit 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(Flatness.TryParseUnit(abbreviation, out FlatnessUnit parsedUnit)); + Assert.Equal(expectedUnit, parsedUnit); + } + + [Theory] + [InlineData("en-US", "I-Units", FlatnessUnit.IUnit)] + [InlineData("en-US", "µm/m", FlatnessUnit.MicrometerPerMeter)] + public void TryParseUnit_WithCurrentCulture(string culture, string abbreviation, FlatnessUnit expectedUnit) + { + using var _ = new CultureScope(culture); + Assert.True(Flatness.TryParseUnit(abbreviation, out FlatnessUnit parsedUnit)); + Assert.Equal(expectedUnit, parsedUnit); + } + + [Theory] + [InlineData("en-US", "I-Units", FlatnessUnit.IUnit)] + [InlineData("en-US", "µm/m", FlatnessUnit.MicrometerPerMeter)] + public void TryParseUnit_WithCulture(string culture, string abbreviation, FlatnessUnit expectedUnit) + { + Assert.True(Flatness.TryParseUnit(abbreviation, CultureInfo.GetCultureInfo(culture), out FlatnessUnit parsedUnit)); + Assert.Equal(expectedUnit, parsedUnit); + } + + [Theory] + [InlineData("en-US", FlatnessUnit.IUnit, "I-Units")] + [InlineData("en-US", FlatnessUnit.MicrometerPerMeter, "µm/m")] + public void GetAbbreviationForCulture(string culture, FlatnessUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Flatness.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Flatness.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Flatness.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit(FlatnessUnit unit) + { + var inBaseUnits = Flatness.From(1.0, Flatness.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(FlatnessUnit unit) + { + var quantity = Flatness.From(3.0, unit); + var toUnitWithSameUnit = quantity.ToUnit(unit); + Assert.Equal(quantity, toUnitWithSameUnit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(FlatnessUnit unit) + { + Assert.All(Flatness.Units.Where(u => u != Flatness.BaseUnit), fromUnit => + { + var quantity = Flatness.From(3.0, fromUnit); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); + }); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public virtual void ToUnit_FromDefaultQuantity_ReturnsQuantityWithGivenUnit(FlatnessUnit unit) + { + var quantity = default(Flatness); + var converted = quantity.ToUnit(unit); + Assert.Equal(converted.Unit, unit); + } + + [Theory] + [MemberData(nameof(UnitTypes))] + public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(FlatnessUnit unit) + { + var quantity = Flatness.From(3, Flatness.BaseUnit); + Flatness 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() + { + Flatness iunit = Flatness.FromIUnits(1); + AssertEx.EqualTolerance(1, Flatness.FromIUnits(iunit.IUnits).IUnits, IUnitsTolerance); + AssertEx.EqualTolerance(1, Flatness.FromMicrometersPerMeter(iunit.MicrometersPerMeter).IUnits, MicrometersPerMeterTolerance); + } + + [Fact] + public void ArithmeticOperators() + { + Flatness v = Flatness.FromIUnits(1); + AssertEx.EqualTolerance(-1, -v.IUnits, IUnitsTolerance); + AssertEx.EqualTolerance(2, (Flatness.FromIUnits(3)-v).IUnits, IUnitsTolerance); + AssertEx.EqualTolerance(2, (v + v).IUnits, IUnitsTolerance); + AssertEx.EqualTolerance(10, (v*10).IUnits, IUnitsTolerance); + AssertEx.EqualTolerance(10, (10*v).IUnits, IUnitsTolerance); + AssertEx.EqualTolerance(2, (Flatness.FromIUnits(10)/5).IUnits, IUnitsTolerance); + AssertEx.EqualTolerance(2, Flatness.FromIUnits(10)/Flatness.FromIUnits(5), IUnitsTolerance); + } + + [Fact] + public void ComparisonOperators() + { + Flatness oneIUnit = Flatness.FromIUnits(1); + Flatness twoIUnits = Flatness.FromIUnits(2); + + Assert.True(oneIUnit < twoIUnits); + Assert.True(oneIUnit <= twoIUnits); + Assert.True(twoIUnits > oneIUnit); + Assert.True(twoIUnits >= oneIUnit); + + Assert.False(oneIUnit > twoIUnits); + Assert.False(oneIUnit >= twoIUnits); + Assert.False(twoIUnits < oneIUnit); + Assert.False(twoIUnits <= oneIUnit); + } + + [Fact] + public void CompareToIsImplemented() + { + Flatness iunit = Flatness.FromIUnits(1); + Assert.Equal(0, iunit.CompareTo(iunit)); + Assert.True(iunit.CompareTo(Flatness.Zero) > 0); + Assert.True(Flatness.Zero.CompareTo(iunit) < 0); + } + + [Fact] + public void CompareToThrowsOnTypeMismatch() + { + Flatness iunit = Flatness.FromIUnits(1); + Assert.Throws(() => iunit.CompareTo(new object())); + } + + [Fact] + public void CompareToThrowsOnNull() + { + Flatness iunit = Flatness.FromIUnits(1); + Assert.Throws(() => iunit.CompareTo(null)); + } + + [Theory] + [InlineData(1, FlatnessUnit.IUnit, 1, FlatnessUnit.IUnit, true)] // Same value and unit. + [InlineData(1, FlatnessUnit.IUnit, 2, FlatnessUnit.IUnit, false)] // Different value. + [InlineData(2, FlatnessUnit.IUnit, 1, FlatnessUnit.MicrometerPerMeter, false)] // Different value and unit. + [InlineData(1, FlatnessUnit.IUnit, 1, FlatnessUnit.MicrometerPerMeter, false)] // Different unit. + public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, FlatnessUnit unitA, double valueB, FlatnessUnit unitB, bool expectEqual) + { + var a = new Flatness(valueA, unitA); + var b = new Flatness(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 = Flatness.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() + { + Flatness iunit = Flatness.FromIUnits(1); + Assert.False(iunit.Equals(new object())); + } + + [Fact] + public void EqualsReturnsFalseOnNull() + { + Flatness iunit = Flatness.FromIUnits(1); + Assert.False(iunit.Equals(null)); + } + + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance(double firstValue, double secondValue) + { + var quantity = Flatness.FromIUnits(firstValue); + var otherQuantity = Flatness.FromIUnits(secondValue); + Flatness maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + var largerTolerance = maxTolerance * 1.1; + var smallerTolerance = maxTolerance / 1.1; + Assert.True(quantity.Equals(quantity, Flatness.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 = Flatness.FromIUnits(1); + var negativeTolerance = Flatness.FromIUnits(-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(Flatness.BaseDimensions is null); + } + + [Fact] + public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() + { + using var _ = new CultureScope("en-US"); + Assert.Equal("1 I-Units", new Flatness(1, FlatnessUnit.IUnit).ToString()); + Assert.Equal("1 µm/m", new Flatness(1, FlatnessUnit.MicrometerPerMeter).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 I-Units", new Flatness(1, FlatnessUnit.IUnit).ToString(swedishCulture)); + Assert.Equal("1 µm/m", new Flatness(1, FlatnessUnit.MicrometerPerMeter).ToString(swedishCulture)); + } + + [Fact] + public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture() + { + var _ = new CultureScope(CultureInfo.InvariantCulture); + Assert.Equal("0.1 I-Units", new Flatness(0.123456, FlatnessUnit.IUnit).ToString("s1")); + Assert.Equal("0.12 I-Units", new Flatness(0.123456, FlatnessUnit.IUnit).ToString("s2")); + Assert.Equal("0.123 I-Units", new Flatness(0.123456, FlatnessUnit.IUnit).ToString("s3")); + Assert.Equal("0.1235 I-Units", new Flatness(0.123456, FlatnessUnit.IUnit).ToString("s4")); + } + + [Fact] + public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixForGivenCulture() + { + var culture = CultureInfo.InvariantCulture; + Assert.Equal("0.1 I-Units", new Flatness(0.123456, FlatnessUnit.IUnit).ToString("s1", culture)); + Assert.Equal("0.12 I-Units", new Flatness(0.123456, FlatnessUnit.IUnit).ToString("s2", culture)); + Assert.Equal("0.123 I-Units", new Flatness(0.123456, FlatnessUnit.IUnit).ToString("s3", culture)); + Assert.Equal("0.1235 I-Units", new Flatness(0.123456, FlatnessUnit.IUnit).ToString("s4", culture)); + } + + [Theory] + [InlineData(null)] + [InlineData("en-US")] + public void ToString_NullFormat_DefaultsToGeneralFormat(string cultureName) + { + var quantity = Flatness.FromIUnits(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 = Flatness.FromIUnits(1.0); + Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); + } + + [Fact] + public void GetHashCode_Equals() + { + var quantity = Flatness.FromIUnits(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 = Flatness.FromIUnits(value); + Assert.Equal(Flatness.FromIUnits(-value), -quantity); + } + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/Flatness.g.cs b/UnitsNet/GeneratedCode/Quantities/Flatness.g.cs new file mode 100644 index 0000000000..0ed2184f47 --- /dev/null +++ b/UnitsNet/GeneratedCode/Quantities/Flatness.g.cs @@ -0,0 +1,744 @@ +//------------------------------------------------------------------------------ +// +// 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 +{ + /// + /// + /// Flatness is a measurement for the deviation of a surface from a perfectly flat surface. + /// + [DataContract] + [DebuggerTypeProxy(typeof(QuantityDisplay))] + public readonly partial struct Flatness : + 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 FlatnessUnit? _unit; + + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class FlatnessInfo: QuantityInfo + { + /// + public FlatnessInfo(string name, FlatnessUnit baseUnit, IEnumerable> unitMappings, Flatness zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public FlatnessInfo(string name, FlatnessUnit baseUnit, IEnumerable> unitMappings, Flatness zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Flatness.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Flatness", typeof(Flatness).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Flatness quantity. + /// + /// A new instance of the class with the default settings. + public static FlatnessInfo CreateDefault() + { + return new FlatnessInfo(nameof(Flatness), DefaultBaseUnit, GetDefaultMappings(), new Flatness(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Flatness 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 FlatnessInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new FlatnessInfo(nameof(Flatness), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Flatness(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of Flatness is IUnit. All conversions, as defined in the , go via this value. + /// + public static FlatnessUnit DefaultBaseUnit { get; } = FlatnessUnit.IUnit; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Flatness. + public static IEnumerable> GetDefaultMappings() + { + yield return new (FlatnessUnit.IUnit, "IUnit", "IUnits", BaseUnits.Undefined); + yield return new (FlatnessUnit.MicrometerPerMeter, "MicrometerPerMeter", "MicrometersPerMeter", BaseUnits.Undefined); + } + } + + static Flatness() + { + Info = FlatnessInfo.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 Flatness(double value, FlatnessUnit 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 Flatness, which is IUnit. All conversions go via this value. + /// + public static FlatnessUnit BaseUnit => Info.BaseUnitInfo.Value; + + /// + /// All units of measurement for the Flatness quantity. + /// + public static IReadOnlyCollection Units => Info.Units; + + /// + /// Gets an instance of this quantity with a value of 0 in the base unit IUnit. + /// + public static Flatness Zero => Info.Zero; + + #endregion + + #region Properties + + /// + /// The numeric value this quantity was constructed with. + /// + public double Value => _value; + + /// + public FlatnessUnit 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 IUnits => As(FlatnessUnit.IUnit); + + /// + /// Gets a value of this quantity converted into + /// + public double MicrometersPerMeter => As(FlatnessUnit.MicrometerPerMeter); + + #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: FlatnessUnit -> BaseUnit + unitConverter.SetConversionFunction(FlatnessUnit.MicrometerPerMeter, FlatnessUnit.IUnit, quantity => quantity.ToUnit(FlatnessUnit.IUnit)); + + // Register in unit converter: BaseUnit <-> BaseUnit + unitConverter.SetConversionFunction(FlatnessUnit.IUnit, FlatnessUnit.IUnit, quantity => quantity); + + // Register in unit converter: BaseUnit -> FlatnessUnit + unitConverter.SetConversionFunction(FlatnessUnit.IUnit, FlatnessUnit.MicrometerPerMeter, quantity => quantity.ToUnit(FlatnessUnit.MicrometerPerMeter)); + } + + /// + /// Get unit abbreviation string. + /// + /// Unit to get abbreviation for. + /// Unit abbreviation string. + public static string GetAbbreviation(FlatnessUnit 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(FlatnessUnit unit, IFormatProvider? provider) + { + return UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit, provider); + } + + #endregion + + #region Static Factory Methods + + /// + /// Creates a from . + /// + public static Flatness FromIUnits(double value) + { + return new Flatness(value, FlatnessUnit.IUnit); + } + + /// + /// Creates a from . + /// + public static Flatness FromMicrometersPerMeter(double value) + { + return new Flatness(value, FlatnessUnit.MicrometerPerMeter); + } + + /// + /// Dynamically convert from value and unit enum to . + /// + /// Value to convert from. + /// Unit to convert from. + /// Flatness unit value. + public static Flatness From(double value, FlatnessUnit fromUnit) + { + return new Flatness(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 Flatness 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 Flatness 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 Flatness 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 Flatness 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 FlatnessUnit 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 FlatnessUnit ParseUnit(string str, IFormatProvider? provider) + { + return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; + } + + /// + public static bool TryParseUnit([NotNullWhen(true)]string? str, out FlatnessUnit 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 FlatnessUnit unit) + { + return UnitParser.Default.TryParse(str, Info, provider, out unit); + } + + #endregion + + #region Arithmetic Operators + + /// Negate the value. + public static Flatness operator -(Flatness right) + { + return new Flatness(-right.Value, right.Unit); + } + + /// Get from adding two . + public static Flatness operator +(Flatness left, Flatness right) + { + return new Flatness(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + } + + /// Get from subtracting two . + public static Flatness operator -(Flatness left, Flatness right) + { + return new Flatness(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + } + + /// Get from multiplying value and . + public static Flatness operator *(double left, Flatness right) + { + return new Flatness(left * right.Value, right.Unit); + } + + /// Get from multiplying value and . + public static Flatness operator *(Flatness left, double right) + { + return new Flatness(left.Value * right, left.Unit); + } + + /// Get from dividing by value. + public static Flatness operator /(Flatness left, double right) + { + return new Flatness(left.Value / right, left.Unit); + } + + /// Get ratio value from dividing by . + public static double operator /(Flatness left, Flatness right) + { + return left.IUnits / right.IUnits; + } + + #endregion + + #region Equality / IComparable + + /// Returns true if less or equal to. + public static bool operator <=(Flatness left, Flatness right) + { + return left.Value <= right.ToUnit(left.Unit).Value; + } + + /// Returns true if greater than or equal to. + public static bool operator >=(Flatness left, Flatness right) + { + return left.Value >= right.ToUnit(left.Unit).Value; + } + + /// Returns true if less than. + public static bool operator <(Flatness left, Flatness right) + { + return left.Value < right.ToUnit(left.Unit).Value; + } + + /// Returns true if greater than. + public static bool operator >(Flatness left, Flatness 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(Flatness other, Flatness tolerance) 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 ==(Flatness left, Flatness 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(Flatness other, Flatness tolerance) 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 !=(Flatness left, Flatness right) + { + return !(left == right); + } + + /// + /// Indicates strict equality of two quantities, where both and are exactly equal. + [Obsolete("Use Equals(Flatness other, Flatness tolerance) 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 Flatness otherQuantity)) + return false; + + return Equals(otherQuantity); + } + + /// + /// Indicates strict equality of two quantities, where both and are exactly equal. + [Obsolete("Use Equals(Flatness other, Flatness tolerance) 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(Flatness 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 Flatness. + 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 Flatness otherQuantity)) throw new ArgumentException("Expected type Flatness.", 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(Flatness 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(FlatnessUnit unit) + { + if (Unit == unit) + return Value; + + return ToUnit(unit).Value; + } + + /// + public double As(UnitKey unitKey) + { + return As(unitKey.ToUnit()); + } + + /// + /// Converts this Flatness to another Flatness with the unit representation . + /// + /// The unit to convert to. + /// A Flatness with the specified unit. + public Flatness ToUnit(FlatnessUnit 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 Flatness with the specified unit. + public Flatness ToUnit(FlatnessUnit 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(Flatness), Unit, typeof(Flatness), unit), out var conversionFunction)) + { + // See if the unit converter has an extensibility conversion registered. + return (Flatness)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(FlatnessUnit unit, [NotNullWhen(true)] out Flatness? converted) + { + if (Unit == unit) + { + converted = this; + return true; + } + + Flatness? convertedOrNull = (Unit, unit) switch + { + // FlatnessUnit -> BaseUnit + (FlatnessUnit.MicrometerPerMeter, FlatnessUnit.IUnit) => new Flatness(_value / 1e1, FlatnessUnit.IUnit), + + // BaseUnit -> FlatnessUnit + (FlatnessUnit.IUnit, FlatnessUnit.MicrometerPerMeter) => new Flatness(_value * 1e1, FlatnessUnit.MicrometerPerMeter), + + _ => 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 FlatnessUnit typedUnit) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FlatnessUnit)} is supported.", nameof(unit)); + + return As(typedUnit); + } + + /// + IQuantity IQuantity.ToUnit(Enum unit) + { + if (!(unit is FlatnessUnit typedUnit)) + throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FlatnessUnit)} is supported.", nameof(unit)); + + return ToUnit(typedUnit, DefaultConversionFunctions); + } + + /// + IQuantity IQuantity.ToUnit(FlatnessUnit 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/Resources/Flatness.restext b/UnitsNet/GeneratedCode/Resources/Flatness.restext new file mode 100644 index 0000000000..369840047f --- /dev/null +++ b/UnitsNet/GeneratedCode/Resources/Flatness.restext @@ -0,0 +1,2 @@ +IUnits=I-Units +MicrometersPerMeter=µm/m diff --git a/UnitsNet/GeneratedCode/Units/FlatnessUnit.g.cs b/UnitsNet/GeneratedCode/Units/FlatnessUnit.g.cs new file mode 100644 index 0000000000..21a93e226a --- /dev/null +++ b/UnitsNet/GeneratedCode/Units/FlatnessUnit.g.cs @@ -0,0 +1,33 @@ +//------------------------------------------------------------------------------ +// +// 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 FlatnessUnit + { + IUnit = 2, + MicrometerPerMeter = 4, + } + + #pragma warning restore 1591 +}